参考博客:http://blog.csdn.net/u013277740/article/details/51737080
最近做用DownloadManager进行自更新升级,下载安装时!发现6.0以上的系统有的机型,下载完成后,无法自动安装,
原来是这么写的,也没注意过:
// 通过Intent安装APK文件
Intent intents = new Intent();
intents.setAction(Intent.ACTION_DEFAULT);
intents.addCategory(Intent.CATEGORY_DEFAULT);
intents.setDataAndType(uri, "application/vnd.android.package-archive");
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
但是最近6.0有些系统安装不了,发现是这句话里的uri问题,
intents.setDataAndType(uri, "application/vnd.android.package-archive");
以前这个uri是通过DownloadManager里面的getUriForDownloadedFile(longid)获取的!而现在上面的这行代码没有获取uri对应的文件的真实路径,没能成功解析这个uri(具体原因,感兴趣的童鞋,可以去看源码!)所以现在我现在换成下面的写法:
Intent intent = new Intent(); intent.setAction(Intent.ACTION_DEFAULT); intent.addCategory(Intent.CATEGORY_DEFAULT); File apkFile = queryDownloadedApk(); if(apkFile.exists()){ intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent);
}
通过queryDownloadedApk()获取真实文件,然后再生成uri = Uri.fromFile(apkFile);
public File queryDownloadedApk() { File targetApkFile = null; if (downloadId != -1) { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(downloadId); query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL); Cursor cur = downloadManager.query(query); if (cur != null) { if (cur.moveToFirst()) { String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); if (!OdyUtil.isEmpty(uriString)) { targetApkFile = new File(Uri.parse(uriString).getPath()); } } cur.close(); } } return targetApkFile; }
当然也可以通过下面的方法getRealFilePath(final Context context, final Uri uri)正确解析DownloadManager里面的getUriForDownloadedFile(long id)获取的uri 然后再放入intents.setDataAndType()方法中:
public String getRealFilePath(final Context context, final Uri uri) { if (null == uri) return null; final String scheme = uri.getScheme(); String data = null; if (scheme == null) data = uri.getPath(); else if (ContentResolver.SCHEME_FILE.equals(scheme)) { data = uri.getPath(); } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null); if (null != cursor) { if (cursor.moveToFirst()) { int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); if (index > -1) { data = cursor.getString(index); } } cursor.close(); } } return data; }下面代码是一个简单的防止重复下载判断:private boolean isNeedDownloadAgain() {