Question

I have a question that bothers me, which I seem to find no answer on Google. I created a small testing app with a piece of code that does something like this:

in MainActivity, I create an instance of SomeClass which has a method that uses a context as a parameter. Inside this method [lets say it is declared like this: public void doSomething(Context context) ], I have a Runnable that runs after a couple of seconds (I tested with 5 seconds), that uses this context to get a SharedPrefs and put some value in it.

Now, after creating this object in MainActivity, and calling this method, I finish it, but in the Logs I can see that the context of the closed Activity is not null, and all that methods content runs successfully. My question is: If I close an Activity and after that, use it's context to do something with it, why doesn't it backfire with some sort of Exception or did I test it the wrong way?

Was it helpful?

Solution

You killed the activity not the application,So it picks up the application context.And hence it is not null.

A similar example

A broadcast in fact has access to context but broadcast is not an activity.This is because of the same fact that it has the context provided by the application.

Update

For the last question in your first comment here's an answer : Few applications are cached by the system and this can be seen in the settings > Applications > cached processes(ice cream sandwich) . As said at sometime it may be cached and hence even after killing the only activity might not actually kill the application context.

i hope it helps you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top