为什么文件未打开?具有依赖项注入的FileProvider

时间:2018-10-25 13:59:06

标签: xamarin xamarin.forms

嗨,所以我进行了依赖注入,以便在共享项目中使用文件提供程序,但是当我打开时就像是空的,因为这表明他打开了文件,但从不显示内容:

FileDevice.cs

namespace AppQ4evo.Services
{
   public interface FileDevice
    {
        Android.Net.Uri GetFileProviderWorking(File file);
    }
}

FileAndroid.cs

[assembly: Xamarin.Forms.Dependency(typeof (FileAndroid))]
namespace AppQ4evo.Droid
{
    public class FileAndroid : FileDevice
    {


       public Android.Net.Uri GetFileProviderWorking(File file)
        {
            Android.Net.Uri uri = FileProvider.GetUriForFile(Android.App.Application.Context, "com.companyname.AppQ4evo.fileprovider", file);
            return uri;
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.AppQ4evo" android:installLocation="preferExternal">
    <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="27" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
    <uses-permission android:name="android.permission.LOCATION_HARDWARE" />
    <uses-permission android:name="android.permission.INSTALL_LOCATION_PROVIDER" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <application android:label="AppQ4evo.Android" android:icon="@drawable/baseline_account_circle_black_18dp">
        <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.companyname.AppQ4evo.fileprovider" android:grantUriPermissions="true" android:exported="false">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
        </provider>
    </application>
</manifest>

Resources / xml / file_path.xml

<?xml version="1.0" encoding="utf-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
   <external-path name="external_files" path="."/>
  <files-path name="files" path="."/>
  <internal-path name="internal_files" path="."/>
   </paths>

Anexos.xaml.cs(只是打开文件的方法)

  private async Task ListAnexos_ItemTapped(object sender, ItemTappedEventArgs e)
        {

            try
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
                if (status != PermissionStatus.Granted)
                {
                    if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage))
                    {
                        await DisplayAlert("Need location", "Gunna need that location", "OK");
                    }

                    var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Storage);
                    //Best practice to always check that the key exists
                    if (results.ContainsKey(Permission.Storage))
                        status = results[Permission.Storage];
                }

                if (status == PermissionStatus.Granted)
                {

                    var nomeFicheiroSelecionado = ListAnexos.SelectedItem.ToString();
                    var nomeEscolhido = nomeFicheiroSelecionado.Split('.')[0];
                    var anexo = Task.Run(() => log.EscolheAnexo(aux, nomeEscolhido)).Result;
                    var bytes = Convert.FromBase64String(anexo);

                    var directory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
                    var file = Path.Combine(directory.ToString(), nomeFicheiroSelecionado);

                    //   File.WriteAllBytes(file, bytes);

                  //  Debug.WriteLine("");


                    using (FileStream fs = new FileStream(file, FileMode.Append, FileAccess.Write))
                    {
                        fs.Write(bytes, 0, bytes.Length);
                    }

                    //   Device.OpenUri(new Uri(file));


                    var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/" + global::Android.OS.Environment.DirectoryDownloads + "/" + nomeFicheiroSelecionado;

                   Java.IO.File filet = new Java.IO.File(externalPath);
                    filet.SetReadable(true);

                    string application = "";
                    string extension = Path.GetExtension(file);


                    switch (extension.ToLower())
                    {
                        case ".txt":
                            application = "text/plain";
                            break;
                        case ".doc":
                        case ".docx":
                            application = "application/msword";
                            break;
                        case ".pdf":
                            application = "application/pdf";
                            break;
                        case ".xls":
                        case ".xlsx":
                            application = "application/vnd.ms-excel";
                            break;
                        case ".jpg":
                        case ".jpeg":
                        case ".png":
                            application = "image/jpeg";
                            break;
                        default:
                            application = "*/*";
                            break;
                    }

                    //   Android.Net.Uri uri = Android.Net.Uri.FromFile(filet);

                     Android.Net.Uri uri = DependencyService.Get<FileDevice>().GetFileProviderWorking(filet);

                    Intent intent = new Intent(Intent.ActionView);
                    intent.SetDataAndType(uri, application);
                    intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);

                    Android.App.Application.Context.StartActivity(intent);


                }
                else if (status != PermissionStatus.Unknown)
                {
                    PopupNavigation.PushAsync(new ErrorPopUp("Acesso negado. Tente novamente"));
                }
            }
        catch (Exception ex)
            {

                PopupNavigation.PushAsync(new ErrorPopUp("Erro: " + ex));
            }
        }

我在做什么错了?

0 个答案:

没有答案