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();
}
}
}
AppUpdataManger appUpdataManger=new AppUpdataManger(getApplicationContext());
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"/>
startService()