Reputation: 1202
This is the navigation of my application:
Activity1
callsActivity2
→Activity2.finish()
, callActivity3
→Activity3.finish()
When Activity3
finishes, it calls the onResume
method of Activity1
. Now how can I pass a value from Activity3
to Activity1
?
Upvotes: 22
Views: 38038
Reputation: 180
On Android it is possible to launch another app of a specified package name, passing an argument to it.
public static void launchApp(Context context, String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if(intent == null) {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_TEXT, "*argument to send*");
context.startActivity(intent);
}
The code below can be used to retrieve the argument in the target app.
public static String getArgument(Activity activity) {
return activity.getIntent().getStringExtra(Intent.EXTRA_TEXT);
}
Only a reference to Activity is needed, this is useful in Unity where it is messy to subclass Activity.
Upvotes: 0
Reputation: 1054
Also there is other technique, you can call startActivity(new Intent(getApplicationContext(),Activity1.class))
method along with the Bundle class to transfer data from activity3 to activity1.
Upvotes: 0
Reputation: 21
Sending an Intent from activity 3 to 1 would require some trigger like a button or perhaps the onStop lifecycle method to send it. Better to have the result be automatically send with the setResult method.
Upvotes: 0
Reputation: 13541
Why even bother following that kind of structure... if three returns to one? Just send an intent with your data from three to one and handle it accordingly.
Upvotes: 0
Reputation: 7850
Umesh shows a good technique but I think you want the opposite direction.
Step 1
When starting Activity 2 and 3, use startActivityForResult
. This allows you handle the result in the calling activity.
startActivityForResult(MY_REQUEST_ID);
Step 2
In Activities 2 and 3, call setResult(int, Intent)
to return a value:
Intent resultData = new Intent();
resultData.putExtra("valueName", "valueData");
setResult(Activity.RESULT_OK, resultData);
finish();
Step 3
In your calling activty, implement onActivityResult
and get the data:
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == MY_REQUEST_ID) {
if (resultCode == RESULT_OK) {
String myValue = data.getStringExtra("valueName");
// use 'myValue' return value here
}
}
}
Edit:
Technique #2
Yes, you can also use global application state by adding a class to your application that extends Application
, see this StackOverflow answer
Upvotes: 47
Reputation: 13666
Use the session id to the signout activity in the intent you're using to start the activity:
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent)
See this tutorial.
Upvotes: 2