Android 带进度条自动下载Apk并自动安装

1.首先注册下载完成后的广播

DownloadCompleteReceiver receiver = new DownloadCompleteReceiver();
		registerReceiver(receiver, new IntentFilter(
				DownloadManager.ACTION_DOWNLOAD_COMPLETE));

同时在AndroidManifest.xml 中需要设置


    


2.消息设置

@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@SuppressLint("NewApi")
		@Override
		public void handleMessage(Message msg) {
			// 0x123 更新返回信息
			if (msg.what == 0x123) {
				// 生成一个提示DIALOG
				Builder builder = new AlertDialog.Builder(MainIndexPage.this);
				builder.setTitle("版本升级");
				builder.setMessage("发现最新版,建议立即更新使用\n是否更新?");
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								// DownloadManagerTool("http://gdown.baidu.com/data/wisegame/4f361bb58e629011/91xiongmaokanshu_5700.apk");
								DownloadManagerTool("http://www.xhjk.com.cn/static/zfwg_py.apk");
								
								//DownloadManagerTool(DownloadUrl);
								showProcessBar();
							}
						});
				builder.setNegativeButton("退出",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								finish();
							}
						});


				AlertDialog dialog = builder.create();
				dialog.getWindow().setType(
						(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
				dialog.setCancelable(false);
				dialog.setCanceledOnTouchOutside(false);
				dialog.show();


			} else if (msg.what == 0x124) {
				// 进度条更新
				mypDialog.setProgress(status);
			} 
		}
	};


3.下载Apk的方法

/**
	 * 下载最新APK 
	 */
	@SuppressLint("NewApi")
	public void DownloadManagerTool(String downloadAddress) {


		Log.d("qwe", "qwe");
		downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
		DownloadManager.Request down = new DownloadManager.Request(
				Uri.parse(downloadAddress));
		// 设置允许使用的网络类型,这里是移动网络和wifi都可以
		// down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE |
		// DownloadManager.Request.NETWORK_WIFI);
		down.setShowRunningNotification(true);
		// 显示下载界面
		down.setVisibleInDownloadsUi(true);
		down.setTitle("goldcard");


		File destDir = new File("taoyuan");
		if (!destDir.exists()) {
			// destDir.mkdirs();
		}

		//安装目录,apk名称
		File prevFile = new File(
				Environment.getExternalStoragePublicDirectory("XX"),
				"XXX.apk");
		if (prevFile.exists()) {
			Log.d("delete", "prev");
			prevFile.delete();
		}


		down.setDestinationInExternalPublicDir("XX", "XXX.apk");
		file = new File(
				Environment.getExternalStoragePublicDirectory("XX"),
				"XXX.apk");
		// 将下载请求放入队列
		downloadId = downloadManager.enqueue(down);
		Log.e("download id", "" + downloadId);
	}

4.下载进度条

/**
	 * 下载进度dialog 
	 */
	private void showProcessBar() {
		mypDialog = new ProgressDialog(this);
		mypDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mypDialog.setTitle("下载");
		mypDialog.setMessage("下载中,请勿离开此页面");
		mypDialog.setProgress(59);
		mypDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "确定",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						mypDialog.dismiss();
					}
				});
		mypDialog.setIndeterminate(false);
		mypDialog.setCancelable(false);
		mypDialog.show();
		new Thread(new Runnable() {

			@SuppressLint("NewApi")
			@Override
			public void run() {

				boolean downloading = true;

				while (downloading) {

					DownloadManager.Query q = new DownloadManager.Query();
					q.setFilterById(downloadId);

					Cursor cursor = downloadManager.query(q);
					cursor.moveToFirst();
					int bytes_downloaded = cursor.getInt(cursor
							.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
					int bytes_total = cursor.getInt(cursor
							.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

					if (cursor.getInt(cursor
							.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
						downloading = false;
					}

					final double dl_progress = ((double) bytes_downloaded / (double) bytes_total) * 100;
					if (dl_progress > status) {
						status += 1;
						handler.sendEmptyMessage(0x124);
					}
					cursor.close();
				}
			}
		}).start();
	}


5.下载完成广播

/**
	 * 接受下载完成广播 
	 */
	class DownloadCompleteReceiver extends BroadcastReceiver {


		@SuppressLint("InlinedApi")
		@Override
		public void onReceive(Context context, Intent intent) {


			if (intent.getAction().equals(
					DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {


				long downId = intent.getLongExtra(
						DownloadManager.EXTRA_DOWNLOAD_ID, -1);
				if (downloadId != downId)
					return;
				mypDialog.dismiss();
				installApk(file);
			}
		}
	}


6.安装Apk的方法

/**
	 * 安装APK 
	 */
	private void installApk(File file) {

		if (file.toString().endsWith(".apk")) {

			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_VIEW);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(Uri.fromFile(file),
					"application/vnd.android.package-archive");
			startActivity(intent);
			finish();
		}
	}




你可能感兴趣的:(Android)