Reputation: 463
I have two activities A and B and the activity A starts B and keeps running. I want to send back some info from B to A which is still running in background.
I'm doing this but B is starting a new A activity instead of using the previous one.
B
Intent intent = new Intent();
intent.setClass(context, ObtenerDatos.class);
intent.putExtra("EXTRA_ID", StationID);
context.startActivity(intent);
finish();
And A gets the data as this:
@Override
public void onResume() {
super.onResume();
Bundle extras = getIntent().getExtras();
if (extras != null) {
String datas= extras.getString("EXTRA_ID");
if (datas!= null) {
// do stuff
}
}
}
What am I doing wrong?
Thanks!
Upvotes: 0
Views: 936
Reputation: 872
What about using startActivityForResult()
from A to start B?
When B is done, just set the result and call finish()
Intent intent = new Intent();
intent.putExtra(DATA_EXTRA, data);
setResult(Activity.RESULT_OK, intent);
finish();
Then, in A you use onActivityResult()
Upvotes: 0
Reputation: 3215
Intent intent = new Intent();
intent.putExtra("EXTRA_ID", StationID);
context.startActivity(intent);
finish();
I think that the problem is the finish(); becouse how can Acvtivity B still run if you finish it?
Upvotes: -1
Reputation: 67189
Typically you use startActivityForResult()
and onActivityResult()
for this (see Starting Activities and Getting Results).
For example, in Activity A:
private static final int B_REQUEST = 0;
// ...
public void onClick(View v) {
Intent bIntent = new Intent(this, ActivityB.class);
startActivityForResult(bIntent, B_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == B_REQUEST && resultCode == Activity.RESULT_OK) {
// Get data out of the data Intent
}
}
In ActivityB when you want to return to Activity A:
Intent data = new Intent();
// use intent.putExtra() to store your result data
setResult(Activity.Result_OK, data);
finish();
Upvotes: 1
Reputation: 5020
You can use flag Intent.FLAG_ACTIVITY_NEW_TASK
. If an activity is already running it will be brought to the front of the screen with the state it was last in instead of creating a new one.
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(context, ObtenerDatos.class);
intent.putExtra("EXTRA_ID", StationID);
context.startActivity(intent);
finish();
Upvotes: 1