本来一直使用友盟自动更新来实现APP的更新提醒,可是因为一些原因,友盟自动更新到10月份就暂停服务了,所以研究了一下DownloadManager来实现版本自动更新。
第一步:
调用服务器接口 检查版本是否需要更新(我好像说了句废话)当然用推送是最好的 否则每一次进入首页都需要请求一次接口
第二步:
检查apk是否下载过,附上检查代码
public static boolean isExistBoolean(String path) {
File file = new File(path);
if (file.exists()) {
return true;
} else {
return false;
}
}
if(下载过){
直接打开apk安装,附上打开apk的方法
public static void openApk(Context context, String fileName) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
context.startActivity(intent);
}
}else{
没下载过,就用DownloadManager下载apk
public static void intoDownloadManager(Context context, String url, String name) {
DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
// 设置下载路径和文件名(要注意这里的down_path,只需要一个文件夹名称,它会自动在手机根目录下生成此文件夹,不需要完成的手机路径)
request.setDestinationInExternalPublicDir(StaticMembers.DOWN_PATH, context.getResources().getString(R.string.app_name) + name + ".apk");
request.setDescription("新版本下载");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setMimeType("application/vnd.android.package-archive");
// 设置为可被媒体扫描器找到
request.allowScanningByMediaScanner();
// 设置为可见和可管理
request.setVisibleInDownloadsUi(true);
long refernece = dManager.enqueue(request);
// 把当前下载的ID保存起来
SharedPreferences sPreferences = context.getSharedPreferences("downloadapp", 0);
sPreferences.edit().putLong("yuanxinapp", refernece).commit();
}
注册广播监听下载完,并且安装apk
public class DownLoadBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
long myDwonloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
SharedPreferences sPreferences = context.getSharedPreferences("downloadapp", 0);
long refernece = sPreferences.getLong("yuanxinapp", 0);
if (refernece == myDwonloadID) {
String serviceString = Context.DOWNLOAD_SERVICE;
DownloadManager dManager = (DownloadManager) context.getSystemService(serviceString);
Intent install = new Intent(Intent.ACTION_VIEW);
Uri downloadFileUri = dManager.getUriForDownloadedFile(myDwonloadID);
install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(install);
}
}
效果如下:
1.提示框
2.下载进度
3.下载完直接打开apk安装
好了,以上就能实现apk的版本更新了,当然,其本质还是一个文件下载的原理,不过有了封装好的工具,我们拿来用就好了。