Search code examples
androidbroadcastreceiver

What is the significance of the Context in Broadcast receiver?


I have a service which I am starting on receiving some broadcast receive. So for starting the service, I can use:

ctx.startService(new Intent(ctx, myservice.class));

or

applicationContext.startService(new Intent(applicationContext, myservice.class)

where ctx is the context received in the broadcast receiver and applicationContext is the saved static variable that I saved in the MainApplication.

So what would be the difference if I use ctx vs applicationContext ?


Solution

  • You should use the Context instance, you received in onReceive(). It's completely OK to use it for purposes like starting service. And be aware of using static inctances of application context. It may lead to memory leaks, and also can become nulled in some cases.