前言
每个应用肯定都会涉及到更新apk,这里给大家带来一个利用安卓原生DownloadManager完成apk下载的util,拷贝代码即可使用!
1.Util代码
package com.lytwsw.weatherad.utils;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
/**
* author: Created by lixiaotong on 2018/10/17
* e-mail: 516030811@qq.com
*/
public class DownloadUtils {
//下载器
private DownloadManager downloadManager;
private Context mContext;
//下载的ID
private long downloadId;
private String name;
private String pathstr;
public DownloadUtils(Context context, String url, String name) {
this.mContext = context;
downloadAPK(url, name);
this.name = name;
}
//下载apk
private void downloadAPK(String url, String name) {
//创建下载任务
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//移动网络情况下是否允许漫游
request.setAllowedOverRoaming(false);
//在通知栏中显示,默认就是显示的
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setTitle("通知标题,随意修改");
request.setDescription("新版***下载中...");
request.setVisibleInDownloadsUi(true);
//设置下载的路径
File file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), name);
request.setDestinationUri(Uri.fromFile(file));
pathstr = file.getAbsolutePath();
//获取DownloadManager
if (downloadManager == null)
downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
//将下载请求加入下载队列,加入下载队列后会给该任务返回一个long型的id,通过该id可以取消任务,重启任务、获取下载的文件等等
if (downloadManager != null) {
downloadId = downloadManager.enqueue(request);
}
//注册广播接收者,监听下载状态
mContext.registerReceiver(receiver,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
//广播监听下载的各个状态
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
checkStatus();
}
};
//检查下载状态
private void checkStatus() {
DownloadManager.Query query = new DownloadManager.Query();
//通过下载的id查找
query.setFilterById(downloadId);
Cursor cursor = downloadManager.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:
//下载完成安装APK
installAPK();
cursor.close();
break;
//下载失败
case DownloadManager.STATUS_FAILED:
Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
cursor.close();
mContext.unregisterReceiver(receiver);
break;
}
}
}
private void installAPK() {
setPermission(pathstr);
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(pathstr));
//参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致 参数3 共享的文件
Uri apkUri = FileProvider.getUriForFile(mContext, "com.lxtwsw.weather.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, name)), "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();
}
}
}
2.在Manifest中,添加provider
注意,放到application里面
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.lxtwsw.weather.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepath" />
</provider>
3.在res目录下新建xml目录,然后创建一个filepath.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths>
<external-path
name="download"
path="" />
</paths>
</resources>
4.Android8.0未知来源权限
在mainfest中添加权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
5.使用
在需要下载apk的地方,直接调用即可
new DownloadUtils(context, appUrl, "***.apk");