Android应用自动更新功能实现使用AsyncTask!


转载自http://my.oschina.net/banxi/blog/57988

其实这个自动更新功能大体就是两个三个步骤:

   (1)检查更新

   (2)下载更新

  (3)安装更新  

    检查更新和下载更新其实可以算是一步.因为都比较简单,都是主要是下载.

    1) 当你有新的版本发布时,在一个位置放一个更新的文件.

里面到少放有最新应用的版本号.然后你拿当前应用的版本号和服务器上的版本号对比,就知道要不要下载更新了.

   2 ) 下载这个过程,对于Java来说不是什么难事,因为Java提供了丰富的API.更何况Android内置了HttpClient可用.

   3) 这个,安装过程,其实就是使用一个打开查看此下载文件的 Intent.


  这时需要考虑的是文件下载后放到哪里,安全否.:

 一般就是先检测SD卡.然后选择一个合适的目录.

private void checkUpdate() {

	RequestFileInfo requestFileInfo = new RequestFileInfo();
	requestFileInfo.fileUrl = "http://www.waitab.com/demo/demo.apk";
	String status = Environment.getExternalStorageState();
	if (!Environment.MEDIA_MOUNTED.equals(status)) {
		ToastUtils.showFailure(getApplicationContext(),
				"SDcard cannot use!");
		return;
	}
	requestFileInfo.saveFilePath = Environment
			.getExternalStoragePublicDirectory(
					Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
	requestFileInfo.saveFileName = "DiTouchClient.apk";
	showHorizontalFragmentDialog(R.string.title_wait,
			R.string.title_download_update);
	new DownlaodUpdateTask().execute(requestFileInfo);

}

上面的进度条显示我已经封装好的了.showHorizontalFragmentDialog()

显然我使用了android-support-v4兼容包来使用Fragment的.


  在进度条中有显示,下载文件大小,已经下载了多少.速度等信息.

   由于涉及到网络操作.所以把这整个逻辑放在AsyncTask中. 

代码如下:

private class DownlaodUpdateTask extends
		AsyncTask<RequestFileInfo, ProgressValue, BasicCallResult> {

	@Override
	protected BasicCallResult doInBackground(RequestFileInfo... params) {
		final RequestFileInfo req = params[0];
		String apkFileName = "";
		try {
			URL url = new URL(req.fileUrl); // throw MalformedURLException
			HttpURLConnection conn = (HttpURLConnection) url
					.openConnection();// throws IOException
			Log.i(TAG, "response code:" + conn.getResponseCode());
			// 1检查网络连接性
			if (HttpURLConnection.HTTP_OK != conn.getResponseCode()) {
				return new BasicCallResult(
						"Can not connect to the update Server! ", false);
			}
			int length = conn.getContentLength();
			double total = StringUtils.bytes2M(length);
			InputStream is = conn.getInputStream();
			File path = new File(req.saveFilePath);
			if (!path.exists())
				path.mkdir();
			File apkFile = new File(req.saveFilePath, req.saveFileName);
			apkFileName = apkFile.getAbsolutePath();
			FileOutputStream fos = new FileOutputStream(apkFile);
			ProgressValue progressValue = new ProgressValue(0, " downlaod…");
			int count = 0;
			long startTime, endTime;
			byte buffer[] = new byte[1024];
			do {
				startTime = System.currentTimeMillis();
				int numread = is.read(buffer);
				endTime = System.currentTimeMillis();
				count += numread;
				if (numread <= 0) {
					// publish end
					break;
				}
				fos.write(buffer, 0, numread);

				double kbPerSecond = Math
						.ceil((endTime - startTime) / 1000f);
				double current = StringUtils.bytes2M(count);
				progressValue.message = String.format(
						"%.2f M/%.2f M\t\t%.2fKb/S", total, current,
						kbPerSecond);
				progressValue.progress = (int) (((float) count / length) * DialogUtil.LONG_PROGRESS_MAX);
				publishProgress(progressValue);

			} while (true);
			fos.flush();
			fos.close();

		} catch (MalformedURLException e) {
			e.printStackTrace();
			return new BasicCallResult("Wrong url! ", false);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new BasicCallResult("Error: " + e.getLocalizedMessage(),
					false);
		}
		BasicCallResult callResult = new BasicCallResult(
				"download finish!", true);
		callResult.result = apkFileName;
		return callResult;
	}

	@Override
	protected void onPostExecute(BasicCallResult result) {
		removeFragmentDialog();
		if (result.ok) {
			installApk(result.result);
		} else {
			ToastUtils.showFailure(getApplicationContext(), result.message);
		}
	}

	@Override
	protected void onProgressUpdate(ProgressValue... values) {
		ProgressValue value = values[0];
		updateProgressDialog(value);

	}

}

/**
 * 安装更新APK.
 * 
 * @param fileUri
 */
private void installApk(String fileUri) {
	Intent intent = new Intent(Intent.ACTION_VIEW);
	intent.setDataAndType(Uri.parse("file://" + fileUri),
			"application/vnd.android.package-archive");
	startActivity(intent);
	this.finish();

}

PS:Java中传递或者返回多个值,我常用的办法就是将数据封装到一个对象中去.上面用到的一些封装对象如下:

传递多个值用对象是因为AsyncTask设计让你传递一个对象作为传递参数,所以传递对象也需要这样使用.

/**
 * 传递给android 设置进度条对象
 * 
 * <a href="http://my.oschina.net/arthor" class="referer" target="_blank">@author</a>  banxi1988
 * 
 */
public final class ProgressValue {
	/**
	 * 需要设置的进度
	 */
	public int progress;
	/**
	 * 提示信息
	 */
	public String message;

	public ProgressValue(int progress, String message) {
		super();
		this.progress = progress;
		this.message = message;
	}

}

基本的调用返回对象:

public class BasicCallResult {
	public String message;
	public boolean ok;
	public String result;

	public BasicCallResult(String message, boolean ok) {
		super();
		this.message = message;
		this.ok = ok;
	}

}

传递下载相关信息..

public class RequestFileInfo {
	public String fileUrl;
	public String saveFilePath;
	public String saveFileName;

}



猜你喜欢

转载自blog.csdn.net/hanguohui3/article/details/17374211