Another Use for getApplicationContext(): Binding and Rotation
I pointed out a good use for a method that I
generally recommend developers avoid,
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
getting it in the new activity via
For example, if you have an
AsyncTask, you can pass it from
the old activity to the new one. Done properly,
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
from the old activity to the new one via
The answer: yes…but only if you bound to the service
this (i.e., the activity
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!