After I install the app and open it, message "app has stopped" appears after which the permission dialog appears for granting camera permission. After I press "Allow" the app closes and when I open it the camera preview is showing so the app is working perfectly. I know that the error appears due to the fact that getCameraInstance() returns a null, which results from the user not granting permission to access camera. I can't make the permission dialog appear first, what should I do?
public class MainActivity extends AppCompatActivity {
public Camera mCamera;
private CameraPreview mPreview;
private static final int requestCode = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(checkCameraHardware(MainActivity.this)){
//Create instance of Camera
mCamera=getCameraInstance();
}else{
Toast.makeText(MainActivity.this, "Cannot find camera", Toast.LENGTH_LONG).show();
}
mPreview = new CameraPreview(MainActivity.this, mCamera);
FrameLayout preview = findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
private boolean checkCameraHardware(Context context){
if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
return true;
}
else{
return false;}
}
public Camera getCameraInstance(){
Camera c = null;
try{
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED){
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.CAMERA}, requestCode);
}
c = Camera.open();
}catch (Exception e){
Log.d(TAG, "Error: " + e.getMessage());
}
return c;
}
}