Access to application class in Broadcast Receiver

Dr.jacky picture Dr.jacky · Jul 18, 2014 · Viewed 13.8k times · Source

I want to check internet connection in Broadcast Receiver; And set result (A boolean flag) to a global variable, to use it on whole application, in if conditions; That if internet is disconnected, set a status imageview in main activity, to red image, and if connected, set it to green.

I followed this topic. But there is no getApplication() in Broadcast Receiver; And iI should use getApplicationContext() instead.

On another side, this topic:

when writing code in a broadcast receiver, which is not a context but is given a context in its onReceive method, you can only call getApplicationContext(). Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver.

  1. What are the concerns?

  2. How can I access to my application class in broadcast Receiver?

  3. Is there better solution to check internet connection, set global variable and change my status imageview?

Answer

Lalit Poptani picture Lalit Poptani · Jul 18, 2014

You can access your Application class in BroadCastReceiver by using its context,

 @Override
 public void onReceive(final Context context, Intent intent) {
   MyApplication mApplication = ((MyApplication)context.getApplicationContext());
 }