Android
Mobile Management
Technology
Mobile Apps
User Guide

How to manage startActivityForResult on Android

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Android development, the startActivityForResult() method has been a fundamental way of managing inter-activity communication. Specifically, it allows one activity to start another for some result, then receive a callback when the result is returned. However, with newer updates in Android development, including the introduction of Jetpack libraries and changes to the activity and fragment APIs, it's vital to understand both the legacy and modern approaches to handling activity results.

Understanding startActivityForResult()

Traditionally, the method startActivityForResult() is used when an activity wants to receive a result from another activity. For instance, you might want to pick a photo from a gallery app or get a user's choice from another activity.

An example usage is as follows:

java
// MainActivity.java
Intent pickPhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhotoIntent, PICK_PHOTO_REQUEST);

Here, PICK_PHOTO_REQUEST is an integer constant that identifies this specific request and will be used later to handle the result.

Receiving the Result

To handle the result, you override onActivityResult() in your activity:

java
1@Override
2protected void onActivityResult(int requestCode, int resultCode, Intent data) {
3    super.onActivityResult(requestCode, resultCode, data);
4    if (requestCode == PICK_PHOTO_REQUEST) {
5        if (resultCode == RESULT_OK) {
6            Uri selectedImage = data.getData();
7            // Handle the image
8        } else {
9            // Handle cancellation
10        }
11    }
12}

In this method, requestCode helps you identify from which request you're processing the result, resultCode tells you if the operation was successful (RESULT_OK), and the data Intent can carry results data.

Migrating to the New ActivityResult API

Given some inherent issues and modern app architecture changes with startActivityForResult(), Google introduced a more robust way to handle activity results with the ActivityResult APIs. The API shifts the focus from handling results in the prescribed onActivityResult callback to handling them as lambda expressions or callbacks at the point of launching the activity.

Basics of the ActivityResult API

Instead of the old approach, now you initiate an activity result with a more specific contract and handle the result with a callback:

  1. Register the Activity Result: This is typically done in your activity or fragment's initialization logic.
java
1    ActivityResultLauncher<Intent> mGetContent = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
2        new ActivityResultCallback<ActivityResult>() {
3            @Override
4            public void onActivityResult(ActivityResult result) {
5                if (result.getResultCode() == Activity.RESULT_OK) {
6                    Intent data = result.getData();
7                    Uri selectedImage = data.getData();
8                    // Handle the image
9                }
10            }
11        });
  1. Launch the Activity: Activating the registered launcher when needed.
java
    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    mGetContent.launch(intent);

Benefits of the ActivityResult API

The new approach leverages a more modular structure that eases the handling of permissions and improves the readability and maintainability of the code:

  • Clarity and Safety: Reduces boilerplate and makes it clearer when reading through the code where the result is handled.
  • Lifecycle Awareness: Handling results in a way that is lifecycle-aware ensures less chance of memory leaks.

Summary Table

FeaturestartActivityForResult()ActivityResult API
Handling methodonActivityResult()Callback within method invoker
Code structureMonolithic with switch-caseModular with specific callbacks
Lifecycle awarenessLowHigh
Integration with fragmentsComplicatedSimplified

Conclusion

Although startActivityForResult() is widely used and familiar to most Android developers, the new ActivityResult APIs offer a more robust and streamlined approach to handling results from activities. It's advisable to migrate to this new paradigm to take advantage of its lifecycle awareness and modular callback structure, aligning with modern Android development practices.


Course illustration
Course illustration

All Rights Reserved.