你应该在AndroidManifest.xml的application标签中设置FileProvider。
<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>
然后在xml文件夹中创建file_paths.xml。
file_paths.xml添加以下代码。
<?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>
那么在你的dependenceService成就中,你应该使用下面的代码。注意: FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".fileprovider", file);第二个属性是你的包名和“.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();
}
}
}
}
}
并且不要忘记在运行时授予读/写权限。为了测试,可以在MainActivity.cs的OnCreate方法中添加如下代码。
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
{
RequestPermissions(new string[] { Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage }, 0);
}
我把pdf文件放到Download文件夹下,我的filePath是DependencyService.Get<IOpenFile>().OpenPDf("/storage/emulated/0/Download/test.pdf");