请求所需权限
如果您的应用程序没有所需的权限,该应用程序必须调用其中一个requestPermissions()方法来请求适当的权限。您的应用程序传递它想要的权限,以及您指定的整数请求代码,以标识此权限请求。此方法是异步的:它立即返回,并在用户响应对话框后,系统调用应用程序的回调方法,将相同的请求代码传递给requestPermissions()。
int MY_PERMISSIONS_REQUEST_Camera=101;
// Here, thisActivity is the current activity
if (ContextCompat.CheckSelfPermission(thisActivity,
Manifest.Permission.Camera)
!= Permission.Granted) {
// Should we show an explanation?
if (ActivityCompat.ShouldShowRequestPermissionRationale(thisActivity,
Manifest.Permission.Camera)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.RequestPermissions(thisActivity,
new String[]{Manifest.Permission.Camera},
MY_PERMISSIONS_REQUEST_Camera);
// MY_PERMISSIONS_REQUEST_Camera is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
处理权限请求响应
当您的应用程序请求权限时,系统会向用户显示一个对话框。用户做出响应后,系统会调用您的应用程序的OnRequestPermissionsResult()方法,并将用户响应传递给它。您的应用程序必须覆盖该方法以查找是否已授予权限。回调传递与您传递给requestPermissions()相同的请求代码。例如,如果应用程序请求相机访问权限,则可能具有以下回调方法:
public override void OnRequestPermissionsResult(int requestCode,
string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_Camera: {
// If request is cancelled, the result arrays are empty.
if (grantResults.Length > 0 && grantResults[0] == Permission.Granted) {
// permission was granted, yay! Do the
// camera-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
以上示例基于Google原始权限文档
在Android Marshmallow中,您需要在运行时请求权限。 您可以使用Xamarin Permissions插件提示所需的权限。
更多细节请查看在Android Marshmallow中请求运行时权限
以下是一个示例:
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);
if (status == PermissionStatus.Granted)
{
//Permission was granted
}