1

I want to call method in Main Activity from Broadcast Receiver. This is my MainActivity

  public class MainActivity extends ActionBarActivity {

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

  public void DisplayConn(){
       if(isNetworkStatusAvailable(getApplicationContext())) {

           Toast.makeText(getApplicationContext(), "internet is available", Toast.LENGTH_LONG).show();
       } else {
           AlertDialog.Builder builder = new AlertDialog.Builder(this);
           builder.setTitle("Error");
           builder.setMessage("No Network Connection").setCancelable(false)

                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           finish();
                       }
                   });
           AlertDialog alert = builder.create();
           alert.show();
       }
   }
}

And this is my BroadcastReceiver

 public class ConnectionReceiver extends BroadcastReceiver {

     public ConnectionReceiver() {
     }

     @Override
     public void onReceive(Context context, Intent intent) {
         MainActivity myAct = new MainActivity();
         myAct.DisplayConn();
     }
 }

So, everytime my Broadcast have receive it will call the methods in my MainActivity. Thanks in Advance.

jvpintang
  • 51
  • 8

1 Answers1

0

You can use LocalBroadcast Manager for sending a local broadcast from your ConnectionReceiver. In the MainActivity you can register your receiver to receive local broadcasts. You can send a local broadcast when onReceive is called, which will be received by your Activity. Then in your activity you can call the method when you receive this local broadcast. This broadcast is only local to your app. So is safe as well. You can see here how to use it: how to use LocalBroadcastManager?.

LocalBroadcastManager is a helper to register for and send broadcasts of Intents to local objects within your process. This is has a number of advantages over sending global broadcasts with sendBroadcast(Intent). One of them is that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.

Community
  • 1
  • 1
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124