当我们用系统的服务DownLoadManager下载完成后,系统会发送一个广播,我们只需要注册一个广播,然后在广播里面写如一些相应的操作。
1、注册广播
completeReceiver = new CompleteReceiver(); registerReceiver(completeReceiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));//注册广播
2、接收广播
//接收到这个广播 class CompleteReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { openFile(intent, context);//启动安装 } }
3、启动安装
//启动安装 private void openFile(Intent intent,Context context){ long myDownLoadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1); //拿到下载的Id SharedPreferences preferences = context.getSharedPreferences("downloadcomplete",0); long refence = preferences.getLong("refernece",0); if (refence == myDownLoadId){ //如果是我们下载完成后发送的广播消息,那么启动并安装 DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Intent updateApk = new Intent(Intent.ACTION_VIEW); Uri downloadFileUri = downloadManager.getUriForDownloadedFile(myDownLoadId); updateApk.setDataAndType(downloadFileUri, "application/vnd.android.package-archive"); updateApk.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(updateApk); } }
时间: 2024-10-29 04:50:55