You should set the FileProvider in the application
tag of AndroidManifest.xml
.
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.boxviewcolordemo" android:installLocation="auto">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
<application android:label="BoxViewColorDemo.Android">
<provider android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
Then create file_paths.xml
in the xml folder.

file_paths.xml
add following code.
<?xml version="1.0" encoding="utf-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>
Then in your dependenceService achievement, you should use following code. Note: FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".fileprovider", file);
the second attribute is you package name and ".fileprovider"
[assembly: Dependency(typeof(OpenPDF))]
namespace BoxViewColorDemo.Droid
{
public class OpenPDF : IOpenFile
{
public void OpenPDf(string filePath)
{
var rs = System.IO.File.Exists(filePath);
if (rs)
{
var context = Android.App.Application.Context;
var file = new Java.IO.File(filePath);
var uri = FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".fileprovider", file);
try
{
var intent = new Intent(Intent.ActionView);
intent.AddCategory(Intent.CategoryDefault);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
intent.AddFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
intent.SetDataAndType(uri, "application/pdf");
context.StartActivity(intent);
}
catch (Exception e)
{
Toast.MakeText(context, e.Message, ToastLength.Long).Show();
}
}
}
}
}
And do not forget to grand the read/write permission at the runtime. For testing, you can add following code to the OnCreate
method of MainActivity.cs
.
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
{
RequestPermissions(new string[] { Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage }, 0);
}
I put the pdf file to the Download folder, my filePath is DependencyService.Get<IOpenFile>().OpenPDf("/storage/emulated/0/Download/test.pdf");
