我使用以下代码来请求FineLocation / CoarseLocation和Camera的权限:
protected override void OnResume()
{
base.OnResume();
txt_TrashSubmitDescriptionTitle = FindViewById<TextView>(Resource.Id.txt_TrashSubmitDescriptionTitle);
var c = ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) == (int)Permission.Granted;
var y = ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessCoarseLocation) == (int)Permission.Granted;
var z = ContextCompat.CheckSelfPermission(this, Manifest.Permission.Camera) == (int)Permission.Granted;
if (c && y && z)
{
StartLocationService();
}
else
{
var requiredPermissions = new string[] { Manifest.Permission.AccessFineLocation, Manifest.Permission.AccessCoarseLocation, Manifest.Permission.Camera };
if (GeneralFunctions.CheckShouldShowRequestPermissionRationaleForPermissions(this, requiredPermissions))
{
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// For example if the user has previously denied the permission.
Snackbar.Make(txt_TrashSubmitDescriptionTitle,
Resource.String.permission_location_rationale,
Snackbar.LengthIndefinite)
.SetAction(Resource.String.ok, new Action<Android.Views.View>(delegate (Android.Views.View x) { ActivityCompat.RequestPermissions(this, requiredPermissions, 2); })).Show();
}
else
{
ActivityCompat.RequestPermissions(this, requiredPermissions, 2);
}
}
}
此函数用于检查是否应显示PermissionRadiale:
public static bool CheckShouldShowRequestPermissionRationaleForPermissions(Activity _activity, string[] requiredPermissions)
{
bool returnBool = false;
foreach(string _permission in requiredPermissions)
{
returnBool = ActivityCompat.ShouldShowRequestPermissionRationale(_activity, _permission);
}
return returnBool;
}
函数OnResume不断被调用而没有特定的错误,我不知道为什么。
有人知道为什么OnResume不断被调用吗?
首先,确保您在Manifest中设置了权限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
如果没有这些,那么应用程序(如OnResume()中的代码一样)将进入无限的OnResume()循环。至少它是在我的测试应用程序中,我的目标是Android 9.0。
设置完成后,如果用户授予所有权限,代码就能正常运行。但是,我仍然会将OnResume()中的RequestPermissions()代码移到OnCreate()或OnStart()上。一个原因是因为用户可以检查“不要再问”,在这种情况下,它可能导致无限循环。
对于某些背景...当显示RequestPermissions()对话框时,您的活动将触发OnPause(),并且当RequestPermissions对话框关闭时,将引发OnRequestPermissionsResult()和OnResume()。这也似乎发生在触发RequestPermissions()但没有可见对话框的情况下。
希望这可以帮助!