在片段中请求使用相机权限
Request use camera permission in a fragment
我正在编写一个应用程序,出于灵活性考虑,我决定在其设计中使用片段,但是当我 运行 该应用程序时,我得到了 nullobjectreference。问题是 fragment 没有等待用户授予权限,因为它是 运行ning 异步的,所以当它创建相机实例时,由于缺乏权限,即使我先检查它们,它也会变为 null。这是 onCreateView 的代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(checkCameraHardware(this.getActivity())){
checkPermissions();
}else {
try {
this.finalize();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
LinearLayout buttonLayout = (LinearLayout)setButton();
mFrameLayout = new FrameLayout(this.getActivity());
FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
frameParams.gravity = Gravity.BOTTOM;
mFrameLayout.setLayoutParams(frameParams);
mFrameLayout.addView(mPreview);
mFrameLayout.addView(buttonLayout);
return mFrameLayout;
}
以及当我创建相机实例时:
private void cameraCreator(){
mCamera = getCameraInstance();
mCamera.setDisplayOrientation(90);
mPreview = new CameraPreview(this.getActivity(), mCamera);
}
我知道我不能仅仅为了请求权限而暂停线程,但我能做什么?
在运行时将片段添加到您的 Activity 并在这样做之前请求许可
我正在编写一个应用程序,出于灵活性考虑,我决定在其设计中使用片段,但是当我 运行 该应用程序时,我得到了 nullobjectreference。问题是 fragment 没有等待用户授予权限,因为它是 运行ning 异步的,所以当它创建相机实例时,由于缺乏权限,即使我先检查它们,它也会变为 null。这是 onCreateView 的代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(checkCameraHardware(this.getActivity())){
checkPermissions();
}else {
try {
this.finalize();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
LinearLayout buttonLayout = (LinearLayout)setButton();
mFrameLayout = new FrameLayout(this.getActivity());
FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
frameParams.gravity = Gravity.BOTTOM;
mFrameLayout.setLayoutParams(frameParams);
mFrameLayout.addView(mPreview);
mFrameLayout.addView(buttonLayout);
return mFrameLayout;
}
以及当我创建相机实例时:
private void cameraCreator(){
mCamera = getCameraInstance();
mCamera.setDisplayOrientation(90);
mPreview = new CameraPreview(this.getActivity(), mCamera);
}
我知道我不能仅仅为了请求权限而暂停线程,但我能做什么?
在运行时将片段添加到您的 Activity 并在这样做之前请求许可