先 要在AndroidManifest.xml文件中添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
然后Activity中设置两个私有静态变量
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE" };
然后在Activity中的onCreate引用方法
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
verifyStoragePermissions(this);
} public void verifyStoragePermissions(Activity activity)
{
try
{
//检测是否有写的权限
var permission = ActivityCompat.CheckSelfPermission(activity,"android.permission.WRITE_EXTERNAL_STORAGE");
if (permission != Android.Content.PM.Permission.Granted)
{
// 没有写的权限,去申请写的权限,会弹出对话框
ActivityCompat.RequestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}
}
catch (Exception ex)
{
Toast.MakeText(activity, ex.Message, ToastLength.Short).Show();
}
}