androidtaskstackbuilder

TaskStackBuilder with startActivityForResult


In my case I have an activity A that calls activity B using startActivityForResult.

Activity B is a form that returns the data to activity A thus the data can be stored in my database.

Moreover, my app launch a notification which starts activity B when clicking and my problem occurs when I try to go back from activity B to activity A because the method "onActivityResult" is never called. I'm not able to simulate the startActivityForResult() when I creating my TaskStackBuilder:

Intent resultIntent = new Intent(this, activityB.class);
// This ensures that navigating backward from the Activity leads out of your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(activityB.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);

NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                .setContentIntent(resultPendingIntent);

Finally, I've added the parent activity for activity B in the manifest.xml:

<activity
    android:name=".activityB"
    android:parentActivityName=".activityA"
    android:windowSoftInputMode="stateHidden">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".activityA"/>
</activity>

Solution

  • As of my knowledge of the Android's framework, the OnActivityResult method is only called when an activity has been started with startActivityForResult() method and the corresponding activity has called the setResult one.

    Android Official Documentation Android TaskStackBuilder:

    Utility class for constructing synthetic back stacks for cross-task navigation

    So I don't think you can say to the framework to go back to the activity using that callback.

    Instead what you could do is put some extras within the Intent and then when you go back in the back stack (to activity A), check inside the initial methods (onCreate or onResume) for extras or arguments that would only be there in case of comming from that last activity (activity B)