/** * 调用系统安装应用 */ public static boolean installApk(Context context, File file) { if (file == null || !file.exists() || !file.isFile()) { return false; } try { Uri uri; Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //设置7.0以上共享文件,分享路径定义在xml/file_paths.xml //String authorities = "${applicationId}.fileprovider"; //String authorities = "com.xx.android.xx.xx.fileprovider"; //uri = FileProvider.getUriForFile(context, authorities, file); uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", file); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { // 7.0以下,共享文件 uri = Uri.fromFile(file); } intent.setDataAndType(uri, "application/vnd.android.package-archive"); context.startActivity(intent); }catch (Exception e){ } return true; }
文件操作权限 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths>
<!-- Context.getFilesDir() + "/path/" -->
<files-path
name="my_files"
path="xx/"/>
<!-- Context.getCacheDir() + "/path/" -->
<cache-path
name="my_cache"
path="xx/"/>
<!-- Context.getExternalFilesDir(null) + "/path/" -->
<external-files-path
name="external-files-path"
path="xx/"/>
<!-- Context.getExternalCacheDir() + "/path/" -->
<external-cache-path
name="name"
path="xx/" />
<!-- Environment.getExternalStorageDirectory() + "/path/" -->
<external-path
name="my_external_path"
path="xx/"/>
<!-- Environment.getExternalStorageDirectory() + "/path/" -->
<external-path
name="external_storage_root"
path="."/>
<external-path
name="download"
path="" />
<external-path
name="external_path"
path="xx/download/" />
<external-path
name="external_path"
path="xx/" />
</paths>
</resources>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_config"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:name=".App">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities"
>
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
network_config.xml <?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config>