使用DownloadManager进行版本更新(兼容7.0)

概述

DownloadManager是Android SDK中封装的下载文件类,可以很方便开发者使用下载文件。其具体看官方APIhttps://developer.android.com/reference/android/app/DownloadManager.html

正文

  1. 使用DownloadManager下载

    public class DownloadUtils {
    
     private DownloadManager mDownloadManager;
     private Context mContext;
     private long downloadId;
     private String apkName;
    
     public DownloadUtils(Context context) {
         mContext = context;
     }
    
     public void download(String url, String name) {
         final String packageName = "com.android.providers.downloads";
         int state = mContext.getPackageManager().getApplicationEnabledSetting(packageName);
         //检测下载管理器是否被禁用
         if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
             || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
             || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
             AlertDialog.Builder builder = new AlertDialog.Builder(mContext).setTitle("温馨提示").setMessage
                 ("系统下载管理器被禁止,需手动打开").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                     dialog.dismiss();
                     try {
                         Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                         intent.setData(Uri.parse("package:" + packageName));
                         mContext.startActivity(intent);
                     } catch (ActivityNotFoundException e) {
                         Intent intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
                         mContext.startActivity(intent);
                     }
                 }
             }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                     dialog.dismiss();
                 }
             });
             builder.create().show();
         } else {
             //正常下载流程
             apkName = name;
             DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
             request.setAllowedOverRoaming(false);
    
             //通知栏显示
             request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
             request.setTitle(AppUtils.getAppName(mContext));
             request.setDescription("正在下载中...");
             request.setVisibleInDownloadsUi(true);
    
             //设置下载的路径
             request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName);
    
             //获取DownloadManager
             mDownloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
             downloadId = mDownloadManager.enqueue(request);
    
             mContext.registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
         }
     }
    
     private BroadcastReceiver mReceiver = new BroadcastReceiver() {
         @Override
         public void onReceive(Context context, Intent intent) {
             checkStatus();
         }
     };
    
     /**
      * 检查下载状态
      */
     private void checkStatus() {
         DownloadManager.Query query = new DownloadManager.Query();
         query.setFilterById(downloadId);
         Cursor cursor = mDownloadManager.query(query);
         if (cursor.moveToFirst()) {
             int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
             switch (status) {
                 //下载暂停
                 case DownloadManager.STATUS_PAUSED:
                     break;
                 //下载延迟
                 case DownloadManager.STATUS_PENDING:
                     break;
                 //正在下载
                 case DownloadManager.STATUS_RUNNING:
                     break;
                 //下载完成
                 case DownloadManager.STATUS_SUCCESSFUL:
                     installAPK();
                     break;
                 //下载失败
                 case DownloadManager.STATUS_FAILED:
                     Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
                     break;
             }
         }
         cursor.close();
     }
    
     /**
      * 7.0兼容
      */
     private void installAPK() {
         File apkFile =
             new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), apkName);
         Intent intent = new Intent(Intent.ACTION_VIEW);
         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
             Uri apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".provider", apkFile);
             intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
             intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
         } else {
             intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
         }
         mContext.startActivity(intent);
     }
    }
  2. 在Manifest中添加使用权限

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  3. 在Manifest中添加7.0私有文件权限

    <provider
     android:name="android.support.v4.content.FileProvider"
     android:authorities="${applicationId}.provider"
     android:exported="false"
     android:grantUriPermissions="true">
     <meta-data
         android:name="android.support.FILE_PROVIDER_PATHS"
         android:resource="@xml/provider_paths"/>
    </provider>
  4. 建立xml私有文件权限配置
    在res中建立xml文件夹,建立provider_paths.xml文件,文件中:

    <?xml version="1.0" encoding="utf-8"?>
    <resources xmlns:android="http://schemas.android.com/apk/res/android">
     <paths>
         <external-path
             name="download"
             path=""/>
     </paths>
    </resources>

后记

  1. 已兼容7.0私有文件权限问题
  2. 对于部分机型默认或者一些原因,下载管理器是被禁用掉的,必须手动开启或者写代码去跳转到设置界面开启,代码中已兼容。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值