有人知道如何在Xamarin上等待用户的读/写存储权限吗?我一直在寻找,但是没有使用插件就找不到很好的解决方案。
我的应用程序不等待用户许可,这意味着当我的代码在设备目录上运行时。 VS返回异常...
当我使用此行代码时,我的应用程序崩溃了:
string path = Android.OS.Environment.ExternalStorageDirectory.Path;
List<string> files1 = System.IO.Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".pdf"))
.ToList();
我不知道这件事是否仅发生在仿真器或真实设备上。
主要活动:
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
{
ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.WriteExternalStorage }, 0);
}
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted)
{
ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.ReadExternalStorage }, 0);
}
global::Xamarin.Forms.Forms.SetFlags("CollectionView_Experimental");
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
我知道这行没有用处:
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
{
ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.WriteExternalStorage }, 0);
}
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted)
{
ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.ReadExternalStorage }, 0);
}
有任何建议吗?
执行该操作之前,请先征得用户许可,并且只有在授予许可的情况下才允许,否则将显示用户警报。
您可以使用PermissionsPlugin
来表示相同,它允许您请求许可,并在授予或拒绝许可时提供状态。请参考此以获取更多详细信息:How to ask user for accessing permission in Xamarin.forms