Jay Vyas Jay Vyas - 5 months ago 57
Android Question

Calling a Activity method from BroadcastReceiver in Android

Here i am creating a online application that depends only on Internet.

So whenever there is a network error it must notifies to the 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 a 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,



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 currently running ?


try this code :

your broadcastreceiver class for internet lost class :

public class InternetLostReceiver extends BroadcastReceiver{
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{

protected void onCreate(Bundle savedInstanceState) {

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

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

protected void onDestroy() {