Android应用版本更新升级实现源代码下载
2015-04-01 13:08:39  By: shinyuu

本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

若资源对你有帮助、浏览后有很大收获、不妨小额打赏我一下、你的鼓励是维持我不断写博客最大动力

想获取DD博客最新代码、你可以扫描下方的二维码、关注DD博客微信公众号(ddblogs)

或者你也可以关注我的新浪微博、了解DD博客的最新动态:DD博客官方微博(dwtedx的微博)

如对资源有任何疑问或觉得仍然有很大的改善空间、可以对该博文进行评论、希望不吝赐教

为保证及时回复、可以使用博客留言板给我留言: DD博客留言板(dwtedx的留言板)

感谢你的访问、祝你生活愉快、工作顺心、欢迎常来逛逛


快速评论


技术评论

  • 该技术还没有评论、赶快抢沙发吧...
DD记账
top
+