我在片段中使用下面的代码从用户获取运行时权限。
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
STORAGE_PERMISSION_CODE);
}
和超越
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 21: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getActivity(), "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
但重写方法未调用
请给我提示,我必须在片段中重写
最佳答案
因为要记住,你必须在行动中而不是在碎片中这样做。你可以用碎片来对付这个棘手的问题,但这不是个好办法
这是在活动中。我检查权限并保存它
private static final int REQUEST_CODE_GET_ACCOUNTS = 101;
private static final int REQUEST_AUDIO_PERMISSION = 102;
@TargetApi(23)
public void checkAudioPermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
playerFragment.setupVisualizerFxAndUI();
return;
}
if (this.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager
.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},
REQUEST_AUDIO_PERMISSION);
} else {
playerFragment.setupVisualizerFxAndUI();
}
}
@TargetApi(23)
public void checkGmailPermission() {
if (isDeviceOnline()) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
showGmailRecFragment(true);
return;
}
if (this.checkSelfPermission(Manifest.permission.GET_ACCOUNTS) != PackageManager
.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.GET_ACCOUNTS},
REQUEST_CODE_GET_ACCOUNTS);
return;
} else {
showGmailRecFragment(true);
}
} else {
Utils.showToast(this, getString(R.string.no_internet));
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
switch (requestCode) {
case REQUEST_CODE_GET_ACCOUNTS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
showGmailRecFragment(true);
} else {
Utils.showToast(this, getString(R.string.accounts_permision_denied));
}
break;
case REQUEST_AUDIO_PERMISSION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
playerFragment.setupVisualizerFxAndUI();
} else {
Utils.showToast(this, getString(R.string.audio_permission_denied));
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
当我想再次检查权限或者用户拒绝权限时,这是在片段上的。同时保存权限
private void setupViewVisualizer() {
if (!isLiveTv && !homeVideo.isVideoType()) {
((PlayerActivity) activity).checkAudioPermission();
} else {
return;
}
}