Android studio 使用原生自带DownloadManager实现app下载更新

安卓中的DownLoadManag是安卓自带的下载类专门用来下载文件,自API9开始就用这个类可以说兼容性是没问题的了,在开发中如果android给我们提供了该工具我们就没必要去重新写,避免了错误和兼容性的发生,下面我就以App下载更新的列子简单的讲下它的使用
 
直接看代码:代码完整直接复制来用
public class AppUpdataManger {
private String tag = "AppUpdataManger";
private DownloadManager downloadManager;
private Context mContext;
private long mTaskId;
private String downloadPath;
private String versionName;

public AppUpdataManger(Context context) {
    this.mContext = context;

}

//广播接收者,接收下载状态
private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        checkDownloadStatus();//检查下载状态
    }
};

//使用系统下载器下载
public void downloadAPK(String versionUrl, String versionName) {
    this.versionName = versionName;
    TLog.e("下载", versionUrl + versionName);
    //将下载请求加入下载队列
    downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    //创建下载任务
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionUrl));
    request.setAllowedOverRoaming(false);//漫游网络是否可以下载
    //设置文件类型,可以在下载结束后自动打开该文件
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(versionUrl));
    request.setMimeType(mimeString);//加入任务队列
    //在通知栏显示,默认就是显示的
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
    //设置通知栏标题
    request.setTitle("Download");
    request.setDescription("OYVFit Downloading...");
    request.setAllowedOverRoaming(false);
    request.setVisibleInDownloadsUi(true);
    //设置下载的路径
    File file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), versionName);
    request.setDestinationUri(Uri.fromFile(file));
    downloadPath = file.getAbsolutePath();
    //加入下载列后会给该任务返回一个long型的id,
    //通过该id可以取消任务,重启任务等等
    mTaskId = downloadManager.enqueue(request);
    //注册广播接收,监听下载状态
    mContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

}


//检查下载状态
private void checkDownloadStatus() {
    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(mTaskId);//赛选下载任务,传入任务ID,可变参数
    Cursor cursor = downloadManager.query(query);
    if (cursor.moveToFirst()) {
        int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
        switch (status) {
            case DownloadManager.STATUS_PAUSED:
                //下载暂停
                TLog.d(tag, "下载暂停");
                break;
            case DownloadManager.STATUS_PENDING:
                //下载延迟
                TLog.d(tag, "下载延迟");
                break;
            case DownloadManager.STATUS_RUNNING:
                //正在下载
                TLog.d(tag, "正在下载");
                break;
            case DownloadManager.STATUS_SUCCESSFUL:
                Toast.makeText(mContext, "下载完成", Toast.LENGTH_LONG).show();
                //打开文件进行安装
                installAPK();
                break;
            case DownloadManager.STATUS_FAILED:
                //下载失败
                TLog.d(tag, "下载失败");
                Toast.makeText(mContext, "更新失败", Toast.LENGTH_LONG).show();
                break;

        }
    }
    cursor.close();
}

//下载到本地后执行安装根据获得的id进行安装
protected void installAPK() {
    setPermission(downloadPath);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    // 由于没有在Activity环境下启动Activity,设置下面的标签
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    //Android 7.0以上要使用FileProvider
    if (Build.VERSION.SDK_INT >= 24) {
        File file = (new File(downloadPath));
        //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
        Uri apkUri = FileProvider.getUriForFile(mContext, "包名路径.fileProvider", file);
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    } else {
        intent.setDataAndType(Uri.fromFile(new File(Environment.DIRECTORY_DOWNLOADS, versionName)), "application/vnd.android.package-archive");
    }
    mContext.startActivity(intent);

}

//修改文件权限
private void setPermission(String absolutePath) {
    String command = "chmod " + "777" + " " + absolutePath;
    Runtime runtime = Runtime.getRuntime();
    try {
        runtime.exec(command);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

在Activity中调用

AppUpdataManger appUpdataManger=new AppUpdataManger(getApplicationContext());
appUpdataManger.downloadAPK(url,"你的应用文件名称(尽量不要用中文).apk");
 

FileProvider 添加

新建文件夹与文件 main\res\xml\file_paths.xml

file_pahs.xml 内容如下

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <paths>
        <external-path name="testname" path=""/>
        <external-files-path name="opensdk_external" path="Images/tmp"/>
        <root-path name="opensdk_root" path=""/>
    </paths>
</resources>

AndroidManifet.xml 中天 provider

   <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="你的包名.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

所需要的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<!-- 访问网络的权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
 
 
个人建议在server中调用免得用户离开这个页面造成停止下载,直接把最上面的那段代码复制到server中
startService()
时调用
下面我也把demo地址贴出来出什么问题了自己去看看
 
demo:地址   http://download.csdn.net/detail/liufatao/9739677
 
 
 
 
 
 
 
 
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值