欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  技术分享

Android应用版本更新升级实现源代码下载

程序员文章站 2022-03-01 13:52:20
...

本Demo实现自动更新功能、通过Service实现apk的下载、并且在通知栏有进度条显示、可自己修改代码存放apk的目录、手机无SD卡也可以、集成到项目也非常简单、只需要传入apk的url和下载的名称即可

Android应用版本更新升级实现源代码下载


下载文件的代码

/***
 * down file
 * @return
 * @throws MalformedURLException
 */
public long downloadUpdateFile(String down_url, String file)
	throws Exception {
	
	int down_step = down_step_custom;// 提示step
	int totalSize;// 文件总大小
	int downloadCount = 0;// 已经下载好的大小
	int updateCount = 0;// 已经上传的文件大小
	
	InputStream inputStream;
	OutputStream outputStream;

	URL url = new URL(down_url);
	HttpURLConnection httpURLConnection = (HttpURLConnection) url
			.openConnection();
	httpURLConnection.setConnectTimeout(TIMEOUT);
	httpURLConnection.setReadTimeout(TIMEOUT);
	// 获取下载文件的size
	totalSize = httpURLConnection.getContentLength();
	
	if (httpURLConnection.getResponseCode() == 404) {
		throw new Exception("fail!");
		//这个地方应该加一个下载失败的处理,但是,
		//因为我们在外面加了一个try---catch,已经处理了Exception,
		//所以不用处理						
	}
	
	inputStream = httpURLConnection.getInputStream();
	// 文件存在则覆盖掉
	outputStream = new FileOutputStream(file, false);
	byte buffer[] = new byte[1024];
	int readsize = 0;
	while ((readsize = inputStream.read(buffer)) != -1) {		
		outputStream.write(buffer, 0, readsize);
		downloadCount  = readsize;// 时时获取下载到的大小
		//每次增张3%
		if (updateCount == 0 || (downloadCount * 100 / 
				totalSize - down_step) >= updateCount) {
			updateCount  = down_step;
			// 改变通知栏
			contentView.setTextViewText(R.id.notificationPercent,
				updateCount   "%");
			contentView.setProgressBar(R.id.notificationProgress, 
				100,updateCount, false);			
			notification.contentView = contentView;
			notificationManager.notify(R.layout.notification_item, 
				notification);			
		}
	}
	if (httpURLConnection != null) {
		httpURLConnection.disconnect();
	}
	inputStream.close();
	outputStream.close();
	
	return downloadCount;
}


调用代码

//update service
Intent intent = new Intent(this,UpdateService.class); 
intent.putExtra("Key_App_Name",appName); 
intent.putExtra("Key_Down_Url",downUrl); 
startService(intent);


源代码下载链接: http://dwtedx.com/download.html?bdkey=s/1kTKKHLl 密码: za3e