0

I have Activity A, Activity B, and a static class in the same application. The scenario is as follows (it's simplified here; it makes more sense in my software):

  1. (in Activity A) mAppctx = this.getApplicationContext();
  2. (in Activity A) StaticClass.appctx = mAppctx;
  3. Activity B is spawned
  4. Assume that Activity A is destroyed by the system while Activity B is running
  5. Activity B does the following (pseudo-code): ..... = StaticClass.appctx.getResources().openRawResource(...);

Is this correct?

Since an application Context belongs to the Application (i.e. to the process), and not to the Activity, I suppose it's correct, and APK resources can be accessed in this way from the static class without any problem. (I know that Activity B could actually ask getApplicationContext() on his own, but the above question is intentionally different.)

Thomas Calc
  • 2,994
  • 3
  • 30
  • 56
  • Just curious as to what situation makes it unwieldy to grab the Context from activity B or pass an application Context along to whatever needs it at that point. – jqpubliq May 17 '12 at 21:20
  • It's more complicated in my software. Actually, the appContext is stored in an object (which is responsible for many other things too), and this object is created by Activity A, and put to a static variable. The static is needed because the object must survive any Activity wipe-outs, i.e. it should exist as long as the process exists.So actually this object uses the appcontext, including the case when Activity B calls a service of this object. – Thomas Calc May 17 '12 at 22:05

1 Answers1

2

Yes, it is correct as both activity and aplication context access same resources.

Gökhan Barış Aker
  • 4,445
  • 5
  • 25
  • 35
  • Related question: assuming all Activities are wiped out (but the process still lives -- this is known optimization used by the Android system to increase start-up times), does the application context remain valid? I.e. is a process with zero Activities considered as a valid Android application, with a valid Application context? – Thomas Calc May 17 '12 at 22:08
  • I lack experience at the scenerio you mentioned. Still if same process instance is still alive, all of it's data, including context, has to remain valid. Again i have no idea if context instance is cleaned during optimization, that you mentioned. Also, pardon my curiosity but why do you need valid context for empty application? – Gökhan Barış Aker May 17 '12 at 22:19
  • It's a bit long to explain here, sorry, as it's big software, developed by a team. The point is, I don't need a context for the empty application, but if an Activity is respawned, it will use the aforementioned (statically stored) object again, which already contains the appContext. Of course, I could re-set this context in this object at Activity.onCreate(), but if not needed, why. – Thomas Calc May 17 '12 at 22:31