发布:2023/12/7 15:19:59作者:大数据 来源:大数据 浏览次数:625
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public bool IsGrantExternalReadWrite(Activity activity) { if (Build.VERSION.SdkInt >= BuildVersionCodes.M && activity.CheckSelfPermission( Manifest.Permission.WriteExternalStorage) != Android.Content.PM.Permission.Granted) { activity.RequestPermissions(new String[]{ Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage }, 1); return false; } return true; } |
1 2 3 4 5 6 7 |
if (!IsGrantExternalReadWrite(this)) { Toast.MakeText(this, "请先设置允许存储权限后,再启动应用程序!", ToastLength.Long).Show(); return; } LoadFiles(); |
xamarin.android对于权限的申请与使用还是和原生实现有区别的,不过稍加理解也不难推断出来。对比android原生态实现:
Android6.0以上的手机都没有权限直接读取外部存储,即使在AndroidManifest.xml加上
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
也没有任何效果,最后查询国外论坛发现6.0以后很多权限都需要主动请求后才能使用,以下为解决方案:
public static boolean isGrantExternalRW(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission(
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
activity.requestPermissions(new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, 1);
return false;
}
return true;
}
在需要使用的地方类似如下调用即可:
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!isGrantExternalRW(getActivity())){
return;
}
//授权成功后的逻辑
...
}
});
上面代码只是判断了是否授权,如果授权了就执行逻辑,如果没有授权则不执行,那么如果需要监听授权是否成功,则需要重写Activity中的onRequestPermissionsResult函数,如下示例:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSIONS_CODE) {
for (int i = 0; i < permissions.length; i++) {
String permission = permissions[i];
int grantResult = grantResults[i];
if (permission.equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
if (grantResult == PackageManager.PERMISSION_GRANTED) {
//授权成功后的逻辑
...
} else {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSIONS_CODE);
}
}
}
}
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4