安卓开发 Fragment中重写onRequestPermissionsResult() 没有被调用 执行
在Fragment类中重写onRequestPermissionsResult(),发现在权限申请后该方法没有被执行。
- 重现:
修改前代码
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
Toast.makeText(getActivity(),"需要授予必要的权限才能继续运行",Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(this.getActivity(), PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (allPermissionsGranted()) {
startCamera(getContext());
} else {
Toast.makeText(getActivity(),"需要授予必要的权限才能继续运行",Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
}
-
原因:
在Fragment中使用ActivityCompat.requestPermissions,只会去调用宿主Activity的onRequestPermissionsResult,而没有调用Fragment的该方法。 -
解决(正确的权限申请姿势):
使用requestPermissions方法即可,该方法是Fragment的类方法,这个方法才会去回调Fragment的onRequestPermissionsResult
修改后代码
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
Toast.makeText(getActivity(),"需要授予必要的权限才能继续运行",Toast.LENGTH_LONG).show();
requestPermissions(PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (allPermissionsGranted()) {
startCamera(getContext());
} else {
Toast.makeText(getActivity(),"需要授予必要的权限才能继续运行",Toast.LENGTH_LONG).show();
requestPermissions(PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
}