How do I open an internally created pdf in Xamarin.Android via a FileProvider in the default system pdf app?

≯℡__Kan透↙ 提交于 2019-12-02 01:22:58
Access Denied

You need to wrap your URI with FileProvider. Since android uri will give you file:// while FileProvider will give you content://, which you actually need:

public static Android.Net.Uri WrapFileWithUri(Context context,Java.IO.File file)
{
    Android.Net.Uri result;
    if (Build.VERSION.SdkInt < (BuildVersionCodes)24)
    {
        result = Android.Net.Uri.FromFile(file);
    }
    else
    {
        result = FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".provider", file);
    }
    return result;
}

File can be createed this way:

var file = new Java.IO.File(filePath); 

Then you can open it:

    public static void View(Context context, string path, string mimeType) 
    {
        Intent viewIntent = new Intent(Intent.ActionView);
        Java.IO.File document = new Java.IO.File(path);            
        viewIntent.SetDataAndType(UriResolver.WrapFileWithUri(context,document),mimeType);            
        viewIntent.SetFlags(ActivityFlags.NewTask);
        viewIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
        context.StartActivity(Intent.CreateChooser(viewIntent, "your text"));
    }

Be aware, that this line

viewIntent.SetDataAndType(UriResolver.WrapFileWithUri(context,document),mimeType);

does not equal to SetData and SetType separate commands.

And yes, you need to add FileProvider to your manifest:

<provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
        </provider>

Also you need to create Resources\xml folder with provider_paths.xml file:

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

</paths>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!