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

当我们用系统的服务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);
        }
    }

 

转载于:https://www.cnblogs.com/819158327fan/p/5011479.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值