Android7.0系統使用Intent跳轉到APK安裝頁
阿新 • • 發佈:2019-01-09
原因
Android N對訪問檔案許可權收回,按照Android N的要求,若要在應用間共享檔案,您應傳送一項 content://URI,並授予 URI 臨時訪問許可權。
而進行此授權的最簡單方式是使用 FileProvider類。
解決方法
1.在manifest中註冊FileProvider
<provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true"> </provider>
2、指定可用的檔案路徑
在專案的res目錄下,建立xml資料夾,並新建一個file_paths.xml檔案。通過這個檔案來指定檔案路徑:
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <files-path name="tangdada" path="download/" /> <external-path有多種指定路徑,在<paths>標籤內應至少包含一種,或者多種。name="tangdada" path="download/" /> </paths>
a、表示應用程式內部儲存區中的檔案/子目錄中的檔案
<files-path name="name" path="image" />
等同於Context.getFileDir() : /data/data/com.xxx.app/files/image
b、表示應用程式內部儲存區快取子目錄中的檔案
<cache-path name="name" path="image" />
等同於Context.getCacheDir() : /data/data/com.xxx.app/cache/image
c、表示外部儲存區根目錄中的檔案
<external-path name="name" path="image" />
等同於Environment.getExternalStorageDirectory() : /storage/emulated/image
d、表示應用程式外部儲存區根目錄中的檔案
<external-files-path name="name" path="image" />
等同於Context.getExternalFilesDir(String) / Context.getExternalFilesDir(null) : /storage/emulated/0/Android/data/com.xxx.app/files/image
e、表示應用程式外部快取區根目錄中的檔案
<external-cache-path name="name" path="image" />
等同於Context.getExternalCacheDir() : /storage/emulated/0/Android/data/com.xxx.app/cache/image
3、引用指定的路徑
在剛才Androidmanifest.xml中宣告的provider進行關聯:
<provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
所以最終安裝apk的方法可以這麼寫了:
File apkfile = new File(mSavePath, mPackageNameString); if (!apkfile.exists()) { return; } Intent i = new Intent(Intent.ACTION_VIEW); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本 Uri apkUri = getUriForFile(mContext, mContext.getApplicationContext().getPackageName() + ".provider", apkfile); //與manifest中定義的provider中的authorities="com.xinchuang.buynow.fileprovider"保持一致 i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); i.setDataAndType(apkUri, "application/vnd.android.package-archive"); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } else { i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); } mContext.startActivity(i); }
在網上找了好多方法 最後參考stackoverflow裡面的才最終解決