您的位置:首页 > 移动开发

检查app版本更新并调用系统下载并显示到通知栏

2016-11-21 17:53 585 查看
1.下载apk代码片段

private void downloadApk(String url, Activity activity) {

DownloadManager downloadManager=(DownloadManager)activity.getSystemService(Context.DOWNLOAD_SERVICE);
// 开始下载
Uri resource = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(resource);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
request.setAllowedOverRoaming(false);
// 设置文件类型
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
request.setMimeType(mimeString);
// 在通知栏中显示
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setVisibleInDownloadsUi(true);
// sdcard的目录下的download文件夹
request.setDestinationInExternalPublicDir("/download/",
url.substring(url.lastIndexOf("/") + 1, url.length()));

request.setTitle(getApplication().getApplicationInfo().loadLabel(getPackageManager()));
//将下载apk的id传给application
long id = downloadManager.enqueue(request);
MyApplication application = (MyApplication) getApplication();
application.downLoadId = id;
}


2.在application中onCreate注册广播

IntentFilter downLoadfilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

BroadcastReceiver downloadReceiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
VersionUtils.installApk(getDownloadedFileName(), context);
unregisterReceiver(downloadReceiver);
}
}
};
registerReceiver(downloadReceiver, downLoadfilter);文件名代码片段


//获取下载apk的名字
//针对安卓7.0,DownloadManager.COLUMN_LOCAL_FILENAME已不适用
private String getDownloadedFileName() {

String fileName = "";

DownloadManager downloadManager = (DownloadManager) getSystemService(Activity.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);

Cursor c = downloadManager.query(query);
while (c.moveToNext()) {
long id = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID));
if (id == downLoadId) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
String fileUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
fileName = Uri.parse(fileUri).getPath();
} else {
fileName = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
}
break;
}
}
if (c!=null){
c.close();
}
return fileName;
}


4.安装apk代码片段

public static void installApk(String path, Context act) {
File apkfile = new File(path);
if (!apkfile.exists()) {
return;
}
// 通过Intent安装APK文件
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
act.startActivity(intent);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  app apk