DownloadManager 下载apk

秦才英
2023-12-01
private void downloadAPK(){
    ToastUtil.middle(mContext,"开始下载最新版本", Toast.LENGTH_SHORT);
    logsUtil.d("下载");
    //下载路径,如果路径无效了,可换成你的下载路径
    String url =URL_DOWNLOAD_APK+news;
    //String url ="http://a8.pc6.com/hyt7/igemuhan.apk";
    String path ="";

    //创建下载任务,downloadUrl就是下载链接
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setMimeType("application/vnd.android.package-archive");//设置文件类型
    //指定下载路径和下载文件名
    request.setDestinationInExternalPublicDir(path, "slab_"+news+".apk");
    request.setNotificationVisibility(VISIBILITY_VISIBLE|VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    //获取下载管理器
    DownloadManager downloadManager= (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    //将下载任务加入下载队列,否则不会进行下载
    long Id = downloadManager.enqueue(request);

    listener(Id);

}
private void listener(final long Id) {
    // 注册广播监听系统的下载完成事件。
    IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

    BroadcastReceiver broadcastReceiver;
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            long ID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (ID == Id) {
                hideLoading();
                ToastUtil.middle(mContext,"下载完成", Toast.LENGTH_SHORT);
            
            }
        }
    };

    registerReceiver(broadcastReceiver, intentFilter);
}
 类似资料: