onrequestpermissionsresult方法grantResults [0]总是返回-1 in 两种情况允许和拒绝请检查下面的代码: -
申请地点许可: -
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
int hasReadStatePermission = getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
if (hasReadStatePermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION}, Constants.RequestCode.KEY_PERMISSION_ACCESS_FINE_LOCATION);
}else {
setLocation();
}
}else {
DialogUtils.dialogTwoButton(getActivity(), "Allow", "Deny", getString(R.string.msg_get_gps_access), new Runnable() {
@Override
public void run() {
setLocation();
}
}, new Runnable() {
@Override
public void run() {
Intent intent=new Intent(getActivity(), ChangeLocationManualyActivity.class);
startActivityForResult(intent,Constants.RequestCode.LOCATION_CHANGE);
}
});
允许回调方法,其中PackageManager.PERMISSION_GRANTED = 0,PackageManager.PERMISSION_DENIED = -1
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(requestCode==Constants.RequestCode.KEY_PERMISSION_ACCESS_FINE_LOCATION)
if(grantResults.length>0&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setLocation();
}else{
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent=new Intent(getActivity(), ChangeLocationManualyActivity.class);
startActivityForResult(intent,Constants.RequestCode.LOCATION_CHANGE);
}
},3000);
}
}
答案 0 :(得分:1)
请查看以下代码: -
public static boolean selfPermissionGranted(Context context, String permission) {
// For Android < Android M, self permissions are always granted.
boolean result = true;
int targetSdkVersion;
try {
final PackageInfo info = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
targetSdkVersion = info.applicationInfo.targetSdkVersion;
} catch (PackageManager.NameNotFoundException e) {
targetSdkVersion = 21;
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (targetSdkVersion >= Build.VERSION_CODES.M) {
// targetSdkVersion >= Android M, we can
// use Context#checkSelfPermission
result = context.checkSelfPermission(permission)
== PackageManager.PERMISSION_GRANTED;
} else {
// targetSdkVersion < Android M, we have to use PermissionChecker
result = PermissionChecker.checkSelfPermission(context, permission)
== PermissionChecker.PERMISSION_GRANTED;
}
}
System.out.println("Result is==>" + result);
return result;
}
给出如下调用: -
if (!selfPermissionGranted(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_ACCESS_COARSE_LOCATION);
}
它为我工作。希望它可以帮到你。
答案 1 :(得分:0)
选中grantResults[1]
代替grantResults[0]
。