Reputation: 110670
When I instantiate a BroadcastReceiver and when onReceive() is get called by android framework, what is the context passed to the onReceive() method? Is that an activity context? of an application context?
Thank you.
Upvotes: 17
Views: 9350
Reputation: 11527
Historically, it's an instance of ReceiverRestrictedContext
, but this class is gone in recent Android versions (don't know which API level exactly, but it's not present in API 26 sources), so now, it should be your Application Context.
ReceiverRestrictedContext
prevented to register a BroadcastReceiver
from a BroadcastReceiver
.
Since an instance of ReceiverRestrictedContext
is created each time your BroadcastReceiver
is instantiated, you have to beware of not passing it to a component having a lifecycle longer than yours (very short lived) BroadcastReceiver
, or you would create memory leaks on these older (not so much as of now) Android versions which have this ReceiverRestrictedContext
.
You can safely call getApplicationContext()
and pass its result to a longer lived component though.
Note that the fact ReceiverRestrictedContext
is gone from recent Android versions doesn't mean you can make a "BroadcastReceiverCeption"!
Upvotes: 6
Reputation: 4917
It's the context in which the receiver is running. For example, if the broadcast message is from UsbManager, the context is the context of UsbManager.
More info: BroadcastReceiver
Upvotes: 0
Reputation: 26991
It Is An Application Context.
public abstract void onReceive (Context context, Intent intent)
Upvotes: 12