A Real Use for getApplicationContext()!
getApplicationContext()
is a seriously overused method.
Most times where I see it, using this
would work just as
well, if not better.
One case where getApplicationContext()
can be useful,
though, lies in the intersection of sticky broadcasts and
BroadcastReceiver
, as discovered through discussions
on this StackOverflow question.
A sticky broadcast is one where Android holds onto the last
Intent
that was broadcast for that action. You can get that
last Intent
by calling registerReceiver()
, with an IntentFilter
that matches the action, but a null
BroadcastReceiver
.
Things get tricky, though, if you try doing that from
the onReceive()
method of a manifest-registered BroadcastReceiver
,
such as an app widget implementation. If you use the Context
object that is passed into onReceive()
and call registerReceiver()
on it, you get an error. The error complains about a BroadcastReceiver
registering another BroadcastReceiver
, despite the fact that,
in this case, you’re actually just trying to get a sticky
broadcast Intent
value.
The workaround, as Ms. Hackborn pointed out, is to use
getApplicationContext()
. That Context
object will
support the registerReceiver()
call, so you can get the
sticky broadcast Intent
value you seek.
Find out about new posts on the CommonsBlog via the Atom feed, or follow @CommonsWare on Twitter!