Search code examples
androidbroadcastreceiverandroid-broadcast

Boot completed broadcast receiver context parameter


I am working on a service that can start at device boot completion, I am setting a preference file to store service running state so I can retrieve it when I need it, in my broadcast receiver:

public class MyServiceBootReceiver extends BroadcastReceiver {
    public MyServiceBootReceiver() {super();}

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            if(MyService.isRunning(context)) //static method to get shared preferences value
            context.startService(new Intent(context, MyService.class));
        }
    }
}

Now I am confused about the "context" parameter in onReceive() method, since the application and all its components will be destroyed when device is shutdown, which context is passed in the receiver, and which component of my application is actually receiving it?


Solution

  • Before calling your BroadcastReceiver, Android will create your app's Application context. You can actually see this happenning if you have your own class that inherits Application and put up a Log on it's onCreate.

    However, the context you receive in your Receiver is restricted: it cannot call registerReceiver() or bindService().

    More information about different types of contexts can be found here.