如何在默认应用程序中打开文件

问题描述 投票:0回答:1

我正在尝试打开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;
                }
            }
c# xamarin xamarin.forms xamarin.android
1个回答
0
投票

尝试使用FileProvider作为PDF路径:

Android.Net.Uri pdfPath = FileProvider.GetUriForFile(context, "com.mydomain.fileprovider", new Java.IO.File(filePath));

在这里找一个例子:https://github.com/xamarin/Essentials/issues/130

© www.soinside.com 2019 - 2024. All rights reserved.