Search code examples
androidregisterforactivityresult

Is registerForActivityResult able to do as ACTION_CHOOSER


I'm using registerForActivityResult for launch camera or gallery, but is registerForActivityResult able to do like Intent.ACTION_CHOOSER ?

cameraLauncher =
    registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
        if (success) {
           // do somthing
        }
    }
galleryLauncher =
    registerForActivityResult(ActivityResultContracts.GetContent()) {
          // do somthing
    }

In old way

val galleryIntent = Intent(Intent.ACTION_GET_CONTENT)
galleryIntent.addCategory(Intent.CATEGORY_OPENABLE)
galleryIntent.type = "image/*"

val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

val chooserIntent = Intent(Intent.ACTION_CHOOSER)
chooserIntent.putExtra(Intent.EXTRA_INTENT, galleryIntent)
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(cameraIntent))
startActivity(chooserIntent)

Solution

  • I did make it work by implementing ActivityResultContracts.StartActivityForResult() which is calling the existing onActivityResult with same parameters as so(example in Java):

    ActivityResultLauncher<Intent> activityForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            YourActivity.this.onActivityResult(PICK_IMAGE_ID, result.getResultCode(), result.getData());
        }
    });
    

    Then you just start it as:

    Intent pickIntent = new Intent(Intent.ACTION_PICK,     
    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageURI);
    Intent chooserIntent = Intent.createChooser(pickIntent, "Choose");
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{takePhotoIntent});
    if(SDK_INT > Build.VERSION_CODES.Q) {
       activityForResult.launch(chooserIntent);
    } else {
       //support for older than android 11
       startActivityForResult(chooserIntent, PICK_IMAGE_ID);
    }
    

    Your AndroidManifest.xml also needs these queries:

    <queries>
        <intent>
            <action android:name="android.media.action.IMAGE_CAPTURE" />
        </intent>
        <intent>
            <action android:name="android.intent.action.PICK" />
            <data android:mimeType="image/*" />
        </intent>
    </queries>
    

    Note that startActivityForResult and onActivityResult are deprecated and will be removed sometime in the future.