Skip to content Skip to sidebar Skip to footer

How Do I Open An Internally Created Pdf In Xamarin.android Via A Fileprovider In The Default System Pdf App?

I created a .pdf file in the private local directory I got via (I try to work with the minimum of permissions): string targetBaseDir = Environment.GetFolderPath( Environment.Sp

Solution 1:

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:

publicstatic 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:

publicstaticvoidView(Context context, string path, string mimeType) 
    {
        Intent viewIntent = newIntent(Intent.ActionView);
        Java.IO.Filedocument = newJava.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:

<providerandroid:name="android.support.v4.content.FileProvider"android:authorities="${applicationId}.provider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid: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"?><pathsxmlns:android="http://schemas.android.com/apk/res/android"><external-pathname="external_files"path="."/><files-pathname="internal_files"path="." /></paths>

Post a Comment for "How Do I Open An Internally Created Pdf In Xamarin.android Via A Fileprovider In The Default System Pdf App?"