Jay Vyas Jay Vyas - 3 months ago 32
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,

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

Answer

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);
}
}
Comments