Since startActivityForResult is deprecated, I'm trying figure how to launch Camera using the new method.
Since startActivityForResult is deprecated, I'm trying figure how to launch Camera using the new method.
Here's an example, you may add some more validations but registerForActivityResult is used.
EDIT:
TakePicture as ianhanniballake mentioned is a simpler way
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.TakePicture(),
new ActivityResultCallback<Boolean>() {
@Override
public void onActivityResult(Boolean result) {
// stuff here
}
});
Take photo and put it into some imageView. Camera permission required
<uses-permission android:name="android.permission.CAMERA"/>
if(permissionGranted){
pickCamera();
}
Uri cam_uri;
public void pickCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From Camera");
cam_uri = requireContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cam_uri);
//startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE); // OLD WAY
startCamera.launch(cameraIntent); // VERY NEW WAY
}
ActivityResultLauncher<Intent> startCamera = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
// There are no request codes
mImageView.setImageURI(cam_uri);
}
}
});