应用更新实现(下载及自动安装)

/**
	 * download the new apk file
	 * 
	 * @param newApkUrl
	 * @return
	 */
	public File downLoadFile(String newApkUrl) {

		final String fileName = "update.apk";
		File tmpFile = new File("/sdcard/update");

		if (!tmpFile.exists()) {
			tmpFile.mkdir();
		}

		final File file = new File("/sdcard/update/" + fileName);

		try {
			URL url = new URL(newApkUrl);
			try {
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				InputStream is = conn.getInputStream();
				FileOutputStream fos = new FileOutputStream(file);
				byte[] buf = new byte[256];
				conn.connect();

				double count = 0;
				if (conn.getResponseCode() >= 400) {
					// 连接超时
					;

				} else {

					while (count <= 100) {
						if (is != null) {
							int numRead = is.read(buf);
							if (numRead <= 0) {
								break;
							} else {
								fos.write(buf, 0, numRead);
							}
						} else {
							break;
						}
					}
				}

				conn.disconnect();
				fos.close();
				is.close();

			} catch (IOException e) {
				e.printStackTrace();
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		return file;

	}

	/**
	 * open the apk file and install it .
	 * 
	 * @param apkFile
	 */
	private void openFile(File apkFile) {

		Log.e("OpenFile", apkFile.getName());
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(apkFile),
				"application/vnd.android.package-archive");

		startActivity(intent);

	}


以上为下载新的APK文件并安装的过程。

 

除此之外,也可实现自动卸载应用,代码实现如下:

Uri packageURI = Uri.parse("package:com.ishine.oldapk");     

 Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);     

 startActivity(uninstallIntent); 


 

 

你可能感兴趣的:(String,File,url,delete,download,byte)