两种类型的权限设置
1. AndroidManifest.xml中添加权限
2. 动态添加权限(有些权限 Android6.0之后需要动态添加权限),在使用到权限时,监测是否授权,没有授权的申请授权。
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.weatherstation.app" android:installLocation="auto"> <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" /> <application android:label="气象生态环境监测系统" android:usesCleartextTraffic="true" android:icon="@drawable/icon"></application> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- 访问网络,网络定位需要上网--> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> </manifest>
动态添加权限(AndroidManifest.xml中也要加入该权限)
Android中的权限申请
class PermisionUtils { private static int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage}; public static bool VerifyStoragePermissions(Activity activity) { var permission = ActivityCompat.CheckSelfPermission(activity, Manifest.Permission.WriteExternalStorage); if (permission == Permission.Denied) { ActivityCompat.RequestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE); return false; } return true; } }
MainActivity.cs中返回
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); }
【推荐】可以在Nuget添加Plugin.Permissions
这个可以对各个Android IOS UWP统一申请权限
protected override void OnAppearing() { base.OnAppearing(); SetPermission(); } private async void SetPermission() { // Granted storage permission var storageStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage); if (storageStatus != PermissionStatus.Granted) { var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Storage }); storageStatus = results[Permission.Storage]; } }