您的位置:首页 > 移动开发 > Android开发

Android--用DownLoadManager下载完成后启动安装

2015-12-01 22:10 411 查看
当我们用系统的服务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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: