Launching the Gallery
If you want to choose an image from the device's Gallery, you can do something like this:
Intent galleryPickerIntent = new Intent();
galleryPickerIntent.setType("image/*");
galleryPickerIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryPickerIntent, "Select an Image"), 203); // Can be any int
This starts a new activity that we expect to give us some kind of result (in this case, it will be an image Uri
).
A common use case is to launch the Gallery when the user clicks a button:
View.OnClickListener openGalleryButtonListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryPickerIntent = new Intent();
galleryPickerIntent.setType("image/*");
galleryPickerIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryPickerIntent, "Select an Image"), 203); // Can be any int
}
};
mOpenGalleryButton.setOnClickListener(openGalleryButtonListener);
This code will either open the Gallery directly, or first show the user a chooser that lets them select which app to use as a source of images.
Receiving results
To receive the image that the user selects, we will use the onActivityResult()
method:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mAuthSessionHelper.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 203) { // the int we used for startActivityForResult()
// You can do anything here. This is just an example.
mSelectedImageUri = data.getData();
mSelectedImageView.setImageURI(mSelectedImageUri);
}
}
I put some example code in the if
block, but what you do there will depend on your app.