发布:2021/10/28 14:51:21作者:管理员 来源:本站 浏览次数:1132
两种类型的权限设置
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];
}
}
复制代码
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4