When switching between activities (via Intents), it may be reasonable to distinguish between who started the activity and which activity is to be started. For that reason, Android allows to transfer a request code to the newly started activity. That activity can check who called it by taking a look at the request code.
So far this is easy. But if an activity is finished, the method onActivityResult of the original activity is called with the request code that the original activity transferred (to the finished activity). If you need to make a distinction which activity has finished, then your request codes should be properly defined. One way to achieve this is to have your request code include the source and the destination activity. If you use many many activities, you should think of an encoding for that, otherwise simply number the different combinations as in the class RequestCodes.
public class RequestCodes { //activity request_codes public final static int START_TO_CHOOSER = 1; public final static int START_TO_SETTINGS = 2; ... }
In the following code snippet, different activities are launched, depending on the button clicked. The method startActivityForResult takes an intent and a request code as parameters. When clicking on the button with the id R.id.settings, the request code RequestCodes.START_TO_SETTINGS is used that tells the activity to be started (i.e. SETTINGS) that the source activity is START.
public void onClick(View target) { int id = target.getId(); switch(id) { case R.id.select: Intent chooserInt = new Intent(this, ChooserAct.class); startActivityForResult(chooserInt, RequestCodes.START_TO_CHOOSER); break; case R.id.settings: Intent settingsInt = new Intent(this, SettingsAct.class); startActivityForResult(settingsInt, RequestCodes.START_TO_SETTINGS); break; default: } }
Upon finishing of the SETTINGS activity, the request code additionally tells the START activity that the SETTINGS activity is the one that triggered the startActivityForResult method call.
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK && requestCode == RequestCodes.START_TO_SETTINGS) { ... } else if (requestCode == RequestCodes.START_TO_CHOOSER) { if (resultCode == RESULT_OK) { ... } else if (resultCode == RESULT_CANCELED) { ... } } }