权限拒绝:与 FileProvider Android 11 手机共享文件时出现安全异常

ket*_*tha 3 android android-fileprovider android-securityexception android-11

我在 Android 11 设备上遇到以下异常,但能够在电子邮件中共享这些文件,没有任何问题。

Java:Lang:SecurityException: Permission Denial:Reading androidx.core.content.FileProvider.uri content://com.example.myapp.fileprovider/external_files_files/images/default_image.jpg from pid= 10847, uid=1000 requires the provider be exported or granUriPermission.
Run Code Online (Sandbox Code Playgroud)

仅当我共享多个文件时,Android 11 设备才会出现问题,否则当我使用 Intent.setdata = uri(singal uri object) 时,单个文件可以正常工作,没有任何问题。

我的代码:

清单文件声明:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
        ...>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.myapp.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>
        ...
    </application>
</manifest>

Run Code Online (Sandbox Code Playgroud)

文件路径

<paths>
    <external-files-path
        name="images"
        path="."/>
</paths>
Run Code Online (Sandbox Code Playgroud)

共享代码。

    ArrayList<Uri> Urilist = new ArrayList<String>();
 
    // Adding multiple files as below.
    File imagePath = new File(Context.getExternalFilesDir(null), "images");
    File newFile = new File(imagePath, "default_image.jpg");
    Uri contentUri = getUriForFile(getContext(), "com.example.myapp.fileprovider", newFile);

    // Logic to add uri here

    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent. ACTION_SEND_MULTIPLE);
    shareIntent.putExtra(Intent.EXTRA_STREAM, Urilist);
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    shareIntent.setType(*/*);

    startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share)));

Run Code Online (Sandbox Code Playgroud)

谢谢。

ket*_*tha 5

我通过替换下面的行解决了这个问题。

startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share)));

启动活动(共享意图);