Jay Reynolds
Jay Reynolds

Reputation: 21

Using a reference to an Activity that isn't currently displayed to start another Activity

If I have a reference (in a non-activity class) to an Activity that isn’t currently being displayed, is there any reason that I shouldn’t use it start another activity?

Example:

Activity A:

Intent anIntent = new Intent(this, ActivityB)
startActivity(anIntent) // happens first

Some Other Non-Activity Class:

Intent anIntent = new Intent(refToActivityA, ActivityC)
startActivity(anIntent) // happens second

Upvotes: 2

Views: 42

Answers (2)

copolii
copolii

Reputation: 14506

The quick answer is don't do it.

You have a reference to an Activity that is not being displayed. For all you know, that Activity could be destroyed. The fact that you have a reference to it doesn't guarantee that it'll be in a valid state. Trying to use it may throw an Exception.

Personally, I hate seeing a crash/ANR popup for an app that I'm not actively using.

Arguably if the activity is in a valid state and you are able to use it to launch the new activity, it's an even more annoying experience for the user: You're hijacking whatever they're doing (which is likely outside of your app now) to bring to foreground another activity from an app that they've recently closed.

Bad experience in both cases. Then again without knowing exactly what it is you're trying to accomplish, it's hard to give a definitive answer. Perhaps reword your question and say what you want to accomplish.

Upvotes: 1

dominicoder
dominicoder

Reputation: 10165

You generally shouldn't hold references to Activities or other contexts unless you have a good reason to do this.

1) If your first activity is no longer being shown, it's subject to being killed by the system and garbage collected. If you hold the reference, though, it can't be garbage collected, resulting in a (potential) memory leak.

2) Saving a reference to an Activity means you're coupling that class to that activity, which is generally bad practice.

3) Launching activities is an Android concept and should generally be controlled by other Android components. Unless your class is some navigation abstraction, it probably shouldn't be starting activities.

Without more information, it's hard to say what you should be doing in your specific case, but generally you should use the most local Context to start the activity (which could be a Service, ContentProvider, BroadcastReceiver, etc) and not hold on to Contexts.

Hope that helps.

Upvotes: 1

Related Questions