2

Suppose I have two Activity classes in my Android app. Inside Activity B, I know that Activity A exists and is instantiated. What's the proper way to access Activity object A from Activity object B?

2
  • I know it's probably not my business, but I can't keep from asking: what do you want to do? Commented Mar 8, 2011 at 19:01
  • You don't. What problem are you trying to solve? Commented Mar 8, 2011 at 19:26

2 Answers 2

2

How can you know Activity A is still around? You can't, the OS handles that and you should not assume to know anything about another activity other than the one that's in the foreground.

If you want to pass data around, use Intents or in some cases, just use static variables.

Sign up to request clarification or add additional context in comments.

4 Comments

Ok, is there a proper place to store application-wide state variables between activities?
Static variables live as long as the process is around but a process can be killed at anytime after any of your activities leaves the foreground. Preferences/local-files storage are meant to store values that are meant to be persistent and application wide.
Thanks. Just one thing -- I actually want the variables not to persist after neither activity is active. Is there a recommended place to store application-wide transient data? Like preferences, but not persistent. (Though I guess I could wipe certain preferences data when the application starts.)
Then you want to use static variable.
1

You cannot access the activity directly. The only mechanism of passing data between activities is Intent mechanism.

2 Comments

Not true at all. During onCreate within an activity, the activity can store a reference of itself to a static variable in a separate class. Any other class can reference that instance and then even access any interfaces implemented by the class. I do this throughout my application.
When the Activity is finished the ref to activity will remain active in the static variable holding the activity reference and gc will not free it ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.