简体   繁体   中英

Xamarin C# “we don't have access to open this file” When I Trying To Open A PDF

MainActivity.cs:

Java.IO.File file = new Java.IO.File(filePath);
        Android.Net.Uri uri = FileProvider.GetUriForFile(this, "com.companyname.quickexam_final.FileProvider", file);
        Intent intent = new Intent(Intent.ActionView);
        intent.SetDataAndType(uri, "application/pdf");
        intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);


        this.StartActivity(intent);

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.quickexam_final" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="20" android:targetSdkVersion="28" />
    <application android:allowBackup="true" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" android:icon="@mipmap/ic_launcher">
        <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.companyname.quickexam_final.FileProvider" android:exported="false" android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
        </provider>
    </application>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
  <external-path name="external_files" path="."/>
</paths>

Then, when I start my app I see a Toast

"We don't have access to open this file."

How can I solve this problem?

I would guess that this is because for persmissions that are regarded as dangerous, you need to explicitly request them. It is not enough just to have them in the manifest. To solve it you should use ActivityCompat.RequestPermissions to explicitly request access to these.

If you check the spec here it lists, for example, "READ_EXTERNAL_STORAGE" as a dangerous permission requiring an explicit prompt. https://developer.android.com/reference/android/Manifest.permission#READ_EXTERNAL_STORAGE

You can see here more about this issue: https://developer.android.com/guide/topics/permissions/overview#dangerous-permission-prompt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM