DownloadManager 下载完成监听,打开安装界面

  1. AndroidManifest.xml

     <receiver android:name=".OpenDownloadReceiver"
         android:enabled="true"
         android:exported="true">
         <intent-filter>
             <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
             <action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"/>
             <data android:mimeType="application/cn.trinea.download.file" />
         </intent-filter>
     </receiver>
    
  2. 实现BroadcastReceiver 接收广播并处理

    public class OpenDownloadReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
    String action = intent.getAction();
    Intent install = new Intent(Intent.ACTION_VIEW);
    install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    //Log.d("DownloadManager", "--download complete: " + intent.getPackage());
    long mid = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
    //Log.d("DownloadManager", "--download complete mid: " + mid);
    if (mid <= 0) {
        Log.d("DownloadManager", "faild install id: " + mid);
        return;
    }

    install(context, mid);
   }



private void install(Context context, long id) {
    DownloadManager.Query query = new DownloadManager.Query();
    DownloadManager dm = (DownloadManager) context
            .getSystemService(Context.DOWNLOAD_SERVICE);
    query.setFilterById(id);
    Cursor cus = dm.query(query);
    if (cus != null) {
        try {
            if (cus.moveToFirst()) {
                String filename = cus
                        .getString(cus
                                .getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                //Log.d("DownloadManager", "--download complete filename: " + filename);
                int status = cus
                        .getInt(cus .getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
                if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    Uri uri = Uri.fromFile(new File(filename));
                    if (uri != null) {
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        install.setDataAndType(uri,
                                "application/vnd.android.package-archive");
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(install);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        } finally {
            cus.close();
        }
    }
}
  1. 注册监听
 OpenDownloadReceiver downloadRecevier = new   OpenDownloadReceiver();
    registerReceiver(downloadRecevier, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容