我有PDF文件要读,但是异常
System.UnauthorizedAccessException:访问路径“/存储/模拟/0/几何图形”被拒绝。
下面的Downloadbtn_click
方法
if (ContextCompat.CheckSelfPermission(this.Context, Manifest.Permission.ReadExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions(this.Activity, new String[] { Manifest.Permission.ReadExternalStorage }, 1);
}
else
{
var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/" + fileName;
//Below line getting exception
System.IO.File.WriteAllBytes(externalPath, PdfBytes);
var pdfPath = Android.Net.Uri.FromFile(new Java.IO.File(externalPath));
Intent intent = new Intent(this.Activity.Intent.Action);
intent.SetDataAndType(pdfPath, "application/pdf");
this.Context.StartActivity(intent);
}
覆盖OnRequestPermissionsResult
方法
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case 1:
{
if (grantResults.Length > 0&& grantResults[0] == Permission.Granted)
{
var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/" + fileName;
System.IO.File.WriteAllBytes(externalPath, bt);
var pdfPath = Android.Net.Uri.FromFile(new Java.IO.File(externalPath));
Intent intent = new Intent(this.Activity.Intent.Action);
this.Context.StartActivity(intent);
}
return;
}
}
}
Menifest文件
<uses-sdk android:minSdkVersion="17" android:targetSdkVersion="27" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
方法OnRequestPermissionsResult
永远不会被调用。当单击下载按钮控件时,直接进入else
部件,作为Menifest.xml
文件中已经提供的权限。
异常获取
System.IO.File.WriteAllBytes(externalPath, PdfBytes);
我怎么才能解决这个恼人的问题。
发布于 2018-09-26 02:02:01
欢迎来到Android 8,我也有这个问题。
事实证明,ReadExternalStorage已经不够了。如果您进入应用程序设置,您将看到没有读或写设置,只有文件访问。要修复问题请求,请同时进行读写权限检查,同时检查它们:
{ Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage }
不是关于写作吗?System.IO.File.WriteAllBytes(externalPath,PdfBytes);
根据医生的说法,它应该适用于阅读,但实际上它对我没有用。
根据文档
权限 在Android8.0之前(API级别为26),如果应用程序在运行时请求权限并被授予权限,系统也会错误地授予应用程序属于同一权限组的其余权限,以及在清单中注册的权限。 对于针对Android8.0的应用程序,这种行为已经得到纠正。该应用程序只被授予它显式请求的权限。但是,一旦用户向应用程序授予权限,该权限组中的所有后续权限请求都会自动被授予。 例如,假设一个应用程序在其清单中同时列出了READ_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE。该应用程序请求READ_EXTERNAL_STORAGE,用户授予它。如果应用程序的目标是API 25或更低,系统也同时授予WRITE_EXTERNAL_STORAGE,因为它属于相同的存储权限组,并且也在清单中注册。如果应用程序的目标是Android8.0 (API 26),那么系统当时只授予READ_EXTERNAL_STORAGE;但是,如果应用程序稍后请求WRITE_EXTERNAL_STORAGE,系统会立即授予该权限,而不会提示用户。
https://stackoverflow.com/questions/52514704
复制