【Android】解決Android 7.0及以上版本文件暴露異常exposed beyond app through Intent.getData()的方法

我們在APP升級的時候進行下載安裝,卻在Android 7.0及以上版本會報錯

 android.os.FileUriExposedException: file:///路徑 exposed beyond app through Intent.getData()

我們可以藉助FileProvider來解決這個問題

1.新建一個filepaths

在項目的res文件夾下新建一個xml文件夾,在xml文件夾新建一個.xml文件

filepaths.xml

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

2.修改AndroidManifest

在AndroidManifest的Application標籤下新增provider標籤

<application
       ......
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme">
        <activity
        .......
        </activity>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.ice.AAAAA.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths"
                />
        </provider>
    </application>

3.java代碼

當apk下載好之後啓動安裝

 Intent intent = new Intent(Intent.ACTION_VIEW);
 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

 Uri uri;
 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
     intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
     //記得修改com.xxx.fileprovider與androidmanifest相同
     uri = FileProvider.getUriForFile(mContext,"com.ice.AAAAA.fileprovider",apkFile);
     intent.setDataAndType(uri,"application/vnd.android.package-archive");
 }else{
     uri = Uri.parse("file://" + apkFile.toString());
 }
 intent.setDataAndType(uri, "application/vnd.android.package-archive");
 mContext.startActivity(intent);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章