Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 1 month ago 9
Android Question

Get extra value from activity that is not started from current activity

I know how to get results from another activity using

startActivityForResult
but the problem is that I have 3 activities A,B and C. The main activity is A, that back button on all activities should return there.

Now when we Open activity B from activity A, and then activity C from activity B. When the back button is pressed on the Activity C, How can I return the result to activity A?

Activity A:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
int result=data.getIntExtra("result", 0);
SetNotification(result);
}
}
}


Activity C:

//This works for activity B which is started directly from activity A
@Override
public void onBackPressed() {
Intent returnIntent = new Intent();
returnIntent.putExtra("result", unreadCount);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}

Answer

"When the back button is pressed on the Activity C, How can I return the result to activity A?"

Do not go back. Go forward, young grasshopper :P

Intent intent = new Intent(this, activityClass);

// FLAG_ACTIVITY_NEW_TASK : If set, this activity will become the start of a new task on this history stack.
// FLAG_ACTIVITY_CLEAR_TOP: If set, and the activity being launched is already running in the current task, 
// then instead of launching a new instance of that activity, all of the other activities on 
// top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

intent.putExtra("result", unreadCount);

startActivity(intent);