Calling a Activity method from BroadcastReceiver in Android

Jay Vyas picture Jay Vyas · Mar 7, 2014 · Viewed 35.1k times · Source

Here I am creating an online application that depends only on Internet.

So whenever there is a network error it must notify user. For that, I have created a BroadcastReciver that receives call when network connection gets lost(Internet).

All this works perfectly. Now what I need is that I have to call a method of Activity from this Broadcast Receiver, where I have created an Alert Dialogue.

I have read many answers on stack-overflow.com that I can declare that method static and call by using only Activity name,

e.g MyActivityName.myMethod()

But I can't declare my method static, because I am using Alert Dialogue there and it shows me error on line,

AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

that Cannot use this in a static context.

So, how can I call a method of Activity(must not static and without starting that activity) from a Broadcast Receiver ?

And can I get Activity(or fragment) name from Broadcast Receiver which is currently running?

Answer

Vijju picture Vijju · Mar 7, 2014

try this code :

your broadcastreceiver class for internet lost class :

public class InternetLostReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
    context.sendBroadcast(new Intent("INTERNET_LOST"));
}
}

in your activity add this for calling broadcast:

public class TestActivity  extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    registerReceiver(broadcastReceiver, new IntentFilter("INTERNET_LOST"));
}

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // internet lost alert dialog method call from here...
    }
};

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(broadcastReceiver);
}
}