我正在尝试为 android M 请求 READ_PHONE_STATE 权限,但它在活动中有效,当我在片段中实现它时,它不显示对话框。这是代码。
if (preference.getToken() == null) {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
requestReadPhoneStatePermission();
} else {
TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
HashMap<String, String> params = new HashMap<String, String>();
params.put("appCode", Constants.TRACKING_ID);
params.put("phone", tm.getDeviceId());
DeviceUserService.getDeviceUser(params, getContext());
bookmark();
}
这是方法requestReadPhoneStatePermission
public void requestReadPhoneStatePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_PHONE_STATE)) {
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_PHONE_STATE}, READ_PHONE_STATE);
}
}
这是 onRequestPermissionsResult 上的代码。
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case READ_PHONE_STATE:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getContext(), "granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "permission not granted", Toast.LENGTH_LONG).show();
}
return;
}
}
我错过了什么?提前致谢。