我正在尝试打开pdf文件,默认为pdf viewer xamarin表单,但我得到例外:
Android.OS.FileUriExposedException:file:///storage/emulated/0/pdfy/pdfik.pdf通过Intent.getData()暴露在app之外
我添加了READ_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE权限,这个:
while (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
{
ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.WriteExternalStorage }, 0);
}
while (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted)
{
ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.ReadExternalStorage}, 0);
}
这就是我试图打开文件的方式:
public bool OpenFile(string filename)
{
Android.Net.Uri uri = Android.Net.Uri.FromFile(new Java.IO.File(filename));
Intent intent = new Intent(Intent.ActionView);
String mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(MimeTypeMap.GetFileExtensionFromUrl((string)uri).ToLower());
intent.SetDataAndType(uri, mimeType);
intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
try
{
Xamarin.Forms.Forms.Context.StartActivity(intent);
//ApplicationContext.StartActivity(intent);
return true;
}
catch (System.Exception ex)
{
Toast.MakeText(Xamarin.Forms.Forms.Context, "No Application Available to View this file", ToastLength.Short).Show();
//Toast.MakeText(ApplicationContext, "No Application Available to View this file", ToastLength.Short).Show();
return false;
}
}
尝试使用FileProvider作为PDF路径:
Android.Net.Uri pdfPath = FileProvider.GetUriForFile(context, "com.mydomain.fileprovider", new Java.IO.File(filePath));