Another Use for getApplicationContext(): Binding and Rotation

Earlier, I pointed out a good use for a method that I generally recommend developers avoid, getApplicationContext(). Recently, Ms. Hackborn pointed out another good use for it, tied to binding of services to activities that might undergo a configuration change, such as an orientation change.

When an activity changes configuration (rotation, dock, locale, etc.), Android wants to destroy and recreate your activities, to ensure you have the right resources, among other reasons. You have the opportunity to pass an object from the old instance of the activity to the new one via onRetainNonConfigurationInstance(), getting it in the new activity via getLastNonConfigurationInstance().

For example, if you have an AsyncTask, you can pass it from the old activity to the new one. Done properly, your AsyncTask will be (mostly) oblivious to the shift and you will not leak memory.

If you have an activity that has bound to a service via bindService(), you have a ServiceConnection object that represents the bound connection. I inquired as to whether it was safe to pass the ServiceConnection from the old activity to the new one via onRetainNonConfigurationInstance().

The answer: yes…but only if you bound to the service using getApplicationContext(), not this (i.e., the activity as Context).

I need to put together some sample code for this scenario. However, this is rather useful for helping to make sure your service does not shut down unexpectedly.


Need Android app development training for your team? Mark Murphy has trained hundreds! Learn more!