廢話不說,上代碼
private void install(String filePath) { Log.i(TAG, "開始執行安裝: " + filePath); File apkFile = new File(filePath); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Log.w(TAG, "版本大於 N ,開始使用 fileProvider 進行安裝"); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Uri contentUri = FileProvider.getUriForFile( mContext , "你的包名.fileprovider" , apkFile); intent.setDataAndType(contentUri, "application/vnd.android.package-archive"); } else { Log.w(TAG, "正常進行安裝"); intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive"); } startActivity(intent); }
代碼說明
關於在代碼中安裝 APK 文件,在 Android N 以后,為了安卓系統為了安全考慮,不能直接訪問軟件,需要使用 fileprovider 機制來訪問、打開 APK 文件。
上面的 if 語句,就是區分軟件運行平台,來對 intent 設置不同的屬性。
適配 Android 各個版本,使用代碼安裝 APK
第一步:
在清單文件(manifests.xml)application 標簽中增加 <provider> 標簽:
<application> <!--其他的配置項--> <provider android:name="android.support.v4.content.FileProvider" android:authorities="你的包名.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider> <!--其他的配置項--> </application>
注意兩點內容:
1. android:authorities="你的包名.fileprovider" 這個屬性要設置成你自己的包名。
2. <meta-data> 標簽下 android:resource="@xml/file_paths" 是要配置的 xml 文件,他的內容如下:
第二步:
在 res/xml 下增加文件: file_paths.xml 該文件內容如下:
<?xml version="1.0" encoding="utf-8"?> <paths> <external-path name="your_name" path="your_path" /> </paths>
上面的兩個屬性要根據自己的使用來配置。
其中 <external-path> 就是手機的外置存儲目錄。
第三步:
在 Java 代碼中使用最上面的代碼,問題解決。
這里面有個要注意的點:
清單文件中的 android:authorities="你的包名.fileprovider" 和 JAVA 代碼中:
Uri contentUri = FileProvider.getUriForFile( mContext , "你的包名.fileprovider" , apkFile);
中綠色背景的字段必須一致,否則會報錯。