Android 7.0以上 適配安裝APK

Android 7.0以上 適配安裝APK

別忘了在清單文件中給上安裝權限

    <!--安裝未知來源應用-->
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
private static void install(Context context, File file) {
 		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+以上版本
            Uri apkUri = FileProvider.getUriForFile(context, "cn.com.chucloud.chefssupplier.fileprovider", file); //與manifest中定義的provider中的authorities="cn.wlantv.kznk.fileprovider"保持一致
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
        }

在mainifest中定義

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="cn.com.chucloud.chefssupplier.fileprovider"
            android:exported="false"
             android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
        </provider>

在res下創建file_paths

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <paths>
        <!--external-path用來指定Uri共享的
            name屬性的值可以隨便填
            path屬性的值表示共享的具體路徑,這裏設置爲空代表將整個SD卡進行共享,當然你也可以共享存放的圖片地址-->
        <external-path name="my_images" path=""/>
    </paths>

</resources>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章