If you need your second activity to return some data to your first activity I recommend you use startActivityForResult() to start your second activity. Then in onResult() in your first activity you can do the work needed.
In First.java where you start Second.java:
Intent intent = new Intent(this, Second.class);
int requestCode = 1; // Or some number you choose
startActivityForResult(intent, requestCode);
The result method:
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
// Collect data from the intent and use it
String value = data.getString("someValue");
}
In Second.java:
Intent intent = new Intent();
intent.putExtra("someValue", "data");
setResult(RESULT_OK, intent);
finish();
If you do not wish to wait for the Second activity to end before you do some work in the First activity, you could instead send a broadcast which the First activity reacts to.
EDIT:
If you need access to some values in your First activity without making a static reference to it, you could consider putting your activities in an ActivityGroup.
So, the ActivityGroup starts the First activity. And then the First activity uses the ActivityGroup to start the Second activity. Then you will have access to the First activity through a call to getParent() in the Second activity.
class MyActivityGroup extends ActivityGroup {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("first", new Intent(this, First.class));
}
public void startChildActivity(Intent intent) {
Window window = getLocalActivityManager().startActivity(id, intent);
if (window != null) {
setContentView(window.getDecorView());
}
}
}
In First.class:
Intent = new Intent(this, Second.class);
((MyActivityGroup) getParent()).startChildActivity("second", intent);
In Second.class:
Activity first = (First) getParent();
本文介绍如何在Android应用中使用startActivityForResult()启动第二个活动,并在第一个活动中通过onActivityResult()方法接收从第二个活动传回的数据。同时讨论了在不等待第二个活动结束时如何进行操作的方法。

1712

被折叠的 条评论
为什么被折叠?



