In my android app I am using the camera to scan barcode. When the activity starts first time, it asks the user to grant camera permissions.
After the user accepts the permission, the camera is not working, only if the user goes away and goes back to activity. And then the camera scanner is working. Therefore I want to restart the activity after the user accepts the permissions.
My code:
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(AddOsivo.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
cameraSource.start(surfaceView.getHolder());
} else {
ActivityCompat.requestPermissions(AddOsivo.this, new
String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
recreate();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
As you can see, in the condition where I am asking permissions, I put recreate();
This is working fine, but there is a problem - The activity is restarting in loop when the permission alert is shown, until the user accepts it. After that everything works fine, but I don't want to restart activity unless the user accepts the permissions.
CodePudding user response:
You should use the onRequestPermissionsResult
callback:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == REQUEST_CAMERA_PERMISSION){
if(hasAllPermissionsGranted(grantResults)){
cameraSource.start(surfaceView.getHolder());
}
}
}
public boolean hasAllPermissionsGranted(@NonNull int[] grantResults) {
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
return false;
}
}
return true;
}
Add this to your class and remove the recreate()
function.