我试图实施Marshmallow的权限支持,但我的代码在" onRequestPermissionsResult"永远不会被称为。
当在一个活动中工作但是在片段中我遇到了问题,即控件没有进入onRequestPermissionsResult()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCheckPermission();
}
在mCheckPermission()中: -
public void mCheckPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSION_REQUEST_COARSE_LOCATION );
}
}
弹出对话框,弹出2个按钮。拒绝和允许。 单击按钮时,控件不会进入onRequestPermissionCheck();
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISSION_REQUEST_COARSE_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity(), "permission granted", Toast.LENGTH_LONG).show();
//call your action
} else {
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
break;
}
}
}
答案 0 :(得分:2)
您需要使用support.v4.app.fragment requestPermission,而不是使用requestPermission的活动版本。 https://developer.android.com/reference/android/support/v4/app/Fragment.html 702
更改 ActivityCompat.requestPermissions(此为新的String [] {android.Manifest.permission.READ_CONTACTS},REQUEST_CONTACT); 至 requestPermissions(new String [] {android.Manifest.permission.READ_CONTACTS},REQUEST_CONTACT);
和onRequestPermissionsResult将被正确调用。