解决用Android N编译版本引起的android.os.FileUriExposedException

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/rocklee/article/details/83376207

          app一般都有检测新版本自动升级的功能, 一但使用Android NSDK版本来编译, app启动安装新apk的时候会出来FileUriExposedException, 我们需要做的是:

          1/修改AndroidManifest.xml, 在application段加入provider内容:

<application
        android:name=".model.MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/icon"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/icon_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

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

      2/在res下建立xml文件夹,并新建file_paths.xml

xml的内容:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path path="Android/data/com.yourcompany.yourapp/" name="files_root" />
    <external-path path="." name="external_storage_root" />
</paths>

3/修改你安装apk的代码:

/*Intent i = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        i.putExtra("EXTRA_RETURN_RESULT", true);
        ((Activity)context).startActivityForResult(i, REQUEST_CODE);*/

        Intent intent = new Intent(Intent.ACTION_VIEW);
//判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", apkfile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        ((Activity)context).startActivity(intent);

猜你喜欢

转载自blog.csdn.net/rocklee/article/details/83376207