这篇文章也是在项目完成之后,项目中用到的一种APP的升级方式,主要效果就是升级之后再通知栏这个栏位中显示下载进度,等下载完成之后自动安装。完美适配Android 8.0。记录下来供后续参考使用。
其中主要用到了几个关键的技术点:
1、权限申请
2、fileProvider的使用
3、Broadcast Receiver的使用。
4、文件下载和安装的工具类
不再赘述,直接看代码。
AndroidManifest.xml中添加的部分:
1、添加权限申请
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
2、添加provider,其中吧package_name换成自己的APP的包名
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="package_name.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/update_provider_paths"/>
</provider>
3、添加activity
<activity
android:name=".activity.AndroidOPermissionActivity"
android:screenOrientation="portrait">
</activity>
4、添加receiver
<receiver android:name="com.xxx.xxx.receiver.ApkInstallReceiver">
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
</intent-filter>
</receiver>
下边开始实现上边提到的每个部分,首先工具类:
1、文件下载工具类
import android.app.DownloadManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
public class FileDownloadManager {
private DownloadManager downloadManager;
private Context context;
private static FileDownloadManager instance;
private FileDownloadManager(Context context) {
downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
this.context = context.getApplicationContext();
}
public static FileDownloadManager getInstance(Context context) {
if (instance == null) {
instance = new FileDownloadManager(context);
}
return instance;
}
/**
* @param uri
* @param title
* @param description
* @return download id
*/
public long startDownload(String uri, String title, String description,String appName) {
DownloadManager.Request req = new DownloadManager.Request(Uri.parse(uri));
//req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
req.setAllowedOverRoaming(false);
req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//设置文件的保存的位置[三种方式]
//第一种
//file:///storage/emulated/0/Android/data/your-package/files/Download/update.apk
req.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, appName+".apk");
//第二种 这种保存位置会导致Android 8.0安装的时候出现”解析软件包时出现问题“的问题
//file:///storage/emulated/0/Download/update.apk
//req.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, appName+".apk");
//第三种 自定义文件路径
//req.setDestinationUri()
// 设置一些基本显示信息
req.setTitle(title);
req.setDescription(description);
//req.setMimeType("application/vnd.android.package-archive");
//异步
return downloadManager.enqueue(req);
//dm.openDownloadedFile()
}
/**
* 获取文件保存的路径
*
* @param downloadId an ID for the download, unique across the system.
* This ID is used to make future calls related to this download.
* @return file path
* @see FileDownloadManager#getDownloadUri(long)
*/
public String getDownloadPath(long