Peter
Peter

Reputation: 11920

Android - Getting activity object from startActivity

I need to get the instance of the Activity that was created when startActivity() is called. However, startActivity() returns a void value.

I guess startActivity() doesn't wait until the Activity is created.

Is there a different way for me to get hold of the activity that was just created on the call to startActivity? Or, perhaps I can create an Activity instance myself and register it somewhere so that startActivity can find it.

Upvotes: 1

Views: 2022

Answers (1)

Joe Malin
Joe Malin

Reputation: 8641

Is the Activity you're trying to look at in your own app, or in another app?

If they're both your Activities, then it might be OK to do what you're trying to do, although Activities ought to remain separated. You might consider using Fragments instead, since they can "communicate" with each other through their parent Activity.

If they're not both in your app, then you can't get the other Activity instance, because by definition it's in another process. Moreover, the Android system prevents it, because it would be a big security hole.

In general, I squint a bit at attempts to get an instance of something outside of your own component, unless it's an instance of something in the system. Communication between components should be by Intent, bound Service features, or content URIs. Passing around instances leaves you open to memory leaks.

Upvotes: 1

Related Questions