zer0stimulus
zer0stimulus

Reputation: 23606

Android: Does an app only have one Context object

I'm confused about the concept of the Context class. I see that it's a base class of Activity, but the Android docs also mentions the Context storing global information about the app environment. So in my app which has 3 activities, does that mean I have 3 distinct Context objects, or do they actually refer to 1 entity?

Also, what is the lifetime of a Context object- does it live until the last component of this activity's process is garbage collected?

Upvotes: 4

Views: 530

Answers (1)

sehugg
sehugg

Reputation: 3605

The Context docs for createPackageContext give a clue to what's going on:

Each call to this method returns a new instance of a Context object; Context objects are not shared, however they share common state (Resources, ClassLoader, etc) so the Context instance itself is fairly lightweight.

Since Activity instances are created/destroyed frequently, and an Activity is-a Context, this makes sense. The Context instance is just a pass-through for various bits of application state which themselves are long-lived, but the instance itself is not.

Upvotes: 3

Related Questions