Reputation: 3944
In my Android app, my main activity creates ActivityB, but I need to get a reference to that Activity so that I can later raise an event on it. I want to do something like:
var intent = new Intent(this, typeof(ActivityB));
intent.PutExtra("Param1", "Some Value");
ActivityB activityB = StartActivityForResult(intent, RATING_REQUEST_CODE);
.
.
.
activityB.SomeEvent();
But of course, this doesn't work because StartActivityForResult returns void, not an Activity.
How can I get a reference to the activity that I just created with StartActivityForResult?
Upvotes: 0
Views: 77
Reputation: 10308
The other answers have covered what you should do instead, but it might be instructive to explain a little more about what's wrong with your question.
How can I get a reference to the activity that I just created with StartActivityForResult?
Calling startActivityForResult
does not create an activity! Think of it as asking the Android framework to create the activity for you sometime soon. When this method returns, activity B does not exist yet. And when the framework has created activity B, activity A will be in an inactive state and may soon cease to exist. (In practice, activity A won't be completely destroyed unless the "don't keep activities" developer option is turned on. But that's an implementation detail that could change in a future Android version. The docs say activity A could be destroyed, so activity B should never count on activity A existing.)
Upvotes: 1
Reputation: 3731
Android doesn't work that way(At least as far as I know).Communication is done through Intent
s. In this case you need to override the onActivityResult
method which is called when you, say finish taking a photo.
Here is an example:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// the request type
if (requestCode == TAKE_PICTURE) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
//intent has the path to the picture that was taken
}
}
}
Edit:
The framework and Runtime handle most of the Activity life cycle for you. Keeping a reference to an Activity
is probably not a good idea as you never(again at least as far as I know) when it might be Garbage collected
Upvotes: 0
Reputation: 1007614
I need to get a reference to that Activity so that I can later raise an event on it
That's not how you do it in Android. Components are loosely coupled; activities do not hold onto other activities. Android destroys and recreates activities in a number of scenarios (rotating the screen, other configuration changes, process termination and restart). References from one activity to another would become obsolete.
A common approach is to use an event bus, such as LocalBroadcastManager
or greenrobot's EventBus. Have Activity B subscribe for events on the bus, and have Activity A post events to the bus.
Upvotes: 4