Android中使用DownloadManager下载并安装apk( 三 )


public class DownloadDialog extends AlertDialog {private Context mContext;private TextView mTextView;private ProgressBar mProgressBar;private View view;protected DownloadDialog(Context context) {super(context);this.mContext = context;}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//设置对话框样式setStyle();//初始化控件initView();}private void initView() {view = View.inflate(mContext,R.layout.dwonlaod_dialog,null);mTextView = (TextView)view.findViewById(R.id.mTextView);mProgressBar = (ProgressBar)view.findViewById(R.id.mProgressBar);setContentView(view);}private void setStyle() {//设置对话框不可取消this.setCancelable(false);//设置触摸对话框外面不可取消this.setCanceledOnTouchOutside(false);DisplayMetrics displaymetrics = new DisplayMetrics();getWindow().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);//获得应用窗口大小WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes();//设置对话框居中显示layoutParams.gravity = Gravity.CENTER;//设置对话框宽度为屏幕的3/5layoutParams.width = (displaymetrics.widthPixels/5)*3;}//设置进度条public void setProgress(int progress){mTextView.setText(progress+"%");mProgressBar.setProgress(progress);}}
创建显示对话框,取消对话框的方法, :

Android中使用DownloadManager下载并安装apk

文章插图
private void showDialog() {if(downloadDialog==null){downloadDialog = new DownloadDialog(this);}if(!downloadDialog.isShowing()){downloadDialog.show();}}
private void canceledDialog() {if(downloadDialog!=null&&downloadDialog.isShowing()){downloadDialog.dismiss();}}
Step 2:通过开始下载
创建一个方法用于下载应用:
private void download() {showDialog();//最好是用单线程池,或者intentServicenew Thread(new DownLoadRunnable(this,url, handler)).start();}
接下来看看在中的具体处理方法:
public class DownLoadRunnable implements Runnable {private String url;private Handler handler;private Context mContext;public DownLoadRunnable(Context context, String url, Handler handler) {this.mContext = context;this.url = url;this.handler = handler;}@Overridepublic void run() {//设置线程优先级为后台,这样当多个线程并发后很多无关紧要的线程分配的CPU时间将会减少,有利于主线程的处理Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);//具体下载方法startDownload();}private long startDownload() {//获得DownloadManager对象DownloadManager downloadManager=(DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);//获得下载id,这是下载任务生成时的唯一id,可通过此id获得下载信息long requestId= downloadManager.enqueue(CreateRequest(url));//查询下载信息方法queryDownloadProgress(requestId,downloadManager);returnrequestId;}private void queryDownloadProgress(long requestId, DownloadManager downloadManager) {DownloadManager.Query query=new DownloadManager.Query();//根据任务编号id查询下载任务信息query.setFilterById(requestId);try {boolean isGoging=true;while (isGoging) {Cursor cursor = downloadManager.query(query);if (cursor != null && cursor.moveToFirst()) {//获得下载状态int state = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));switch (state) {case DownloadManager.STATUS_SUCCESSFUL://下载成功isGoging=false;handler.obtainMessage(downloadManager.STATUS_SUCCESSFUL).sendToTarget();//发送到主线程,更新uibreak;case DownloadManager.STATUS_FAILED://下载失败isGoging=false;handler.obtainMessage(downloadManager.STATUS_FAILED).sendToTarget();//发送到主线程,更新uibreak;case DownloadManager.STATUS_RUNNING://下载中/*** 计算下载下载率;*/int totalSize = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));int currentSize = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));int progress = (int) (((float) currentSize) / ((float) totalSize) * 100);handler.obtainMessage(downloadManager.STATUS_RUNNING, progress).sendToTarget();//发送到主线程,更新uibreak;case DownloadManager.STATUS_PAUSED://下载停止handler.obtainMessage(DownloadManager.STATUS_PAUSED).sendToTarget();break;case DownloadManager.STATUS_PENDING://准备下载handler.obtainMessage(DownloadManager.STATUS_PENDING).sendToTarget();break;}}if(cursor!=null){cursor.close();}}}catch (Exception e){e.printStackTrace();}}private DownloadManager.Request CreateRequest(String url) {DownloadManager.Requestrequest=new DownloadManager.Request(Uri.parse(url));request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);// 隐藏notificationrequest.setAllowedNetworkTypes(request.NETWORK_WIFI);//设置下载网络环境为wifirequest.setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS,"MyApp.app");//指定apk缓存路径,默认是在SD卡中的Download文件夹returnrequest;}}