Android7.0應用內升級
最近線上項目在7.0機器上出現應用內升級失敗,原來是由於Android7.0權限問題導致。
如果項目的 targetSdkVersion>=24 在處理應用內升級的時候需要兼容7.0。
1、創建file_paths.xml文件
在res下創建xml文件夾,然后在xml文件夾下創建file_paths.xml文件。
1 <?xml version="1.0" encoding="utf-8"?> 2 <resources xmlns:android="http://schemas.android.com/apk/res/android"> 3 <paths> 4 <external-path 5 name="download" 6 path=""/> 7 </paths> 8 </resources>
說明:apk是下載在Environment.getExternalStorageDirectory()路徑下的。
external-path代表 Environment.getExternalStorageDirectory()目錄。
name:必須有。為Environment.getExternalStorageDirectory()的別名
path:可以為空。空代表Environment.getExternalStorageDirectory()目錄下所有的文件夾和文件。
2、配置AndroidManifest.xml文件添加provider標簽
1 <provider 2 android:name="android.support.v4.content.FileProvider" 3 android:authorities="com.ntjr.std.provider" 4 android:exported="false" 5 android:grantUriPermissions="true" 6 > 7 <meta-data 8 android:name="android.support.FILE_PROVIDER_PATHS" 9 android:resource="@xml/file_paths"/> 10 </provider>
3、安裝apk的方法進行版本判斷:
1 public void installApk(Context context, File file) { 2 if (!file.exists()) { 3 ToastUtil.show(mContext, "安裝失敗"); 4 return; 5 } 6 Intent intent = new Intent(); 7 intent.setAction(android.content.Intent.ACTION_VIEW);
//版本>=24 8 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//參數說明:
context:上下文
authority:必須和provider中聲明的android:authorities值一致
file:所下載的apk文件
9 Uri contentUri = FileProvider.getUriForFile(context, "com.ntjr.std.provider", file); 10 intent.setDataAndType(contentUri, "application/vnd.android.package-archive"); 11 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 13 } else { 14 Uri uri = Uri.fromFile(file); 15 intent.setDataAndType(uri, "application/vnd.android.package-archive"); 16 } 17 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 18 context.startActivity(intent); 19 }
要注意使用的是 addFlags還是setFlags。setFlags會清除掉上面所設置的flag。