Search code examples
androidandroid-activitybroadcastreceiver

is context in BroadcastReceiver.onReceive always the activity that calls registerReceiver?


My activity has registered a BroadcastReceiver using registerReceiver(). I would like to update some UI when a broadcast is received. In my experiment I found the context happen to be my activity(singleinstance),

public void onReceive(Context context, Intent intent) {
        Log.d(tag, context.getClass().getName());
}

but I am not sure if it is always the case as the docs are not clear about it.
Can I just cast the context parameter to my activity?

What would be a good practice to change activity in BroadcastReceiver.onReceive?


Solution

  • If you want Update UI, take one Receiver as inner class of activity and broadcast action. Now catch inside onReceive() and update activity. You should unregister it after use is over and context is always of the activity that register broadcast as a onReceive(). You can send a broadcast from service to initiate the update if you are doing calculation in service.