Maggie
Maggie

Reputation: 8081

android communicate between activity and broadcast receiver

I have an activity which displays some data fetched from the server. If no connection is available, activity displays some cached data; if connection is available, activity fetches data and displays it. It all works as expected.
Now, I would like to make my activity reload the data as soon as the connection occurs. I am using a simple Receiver that extends the BroadcastReceiver:

public class ConnectionChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null) {
            //what to do here? 
        } 
     }
}

Broadcast receiver is declared in my manifest file as follows:

<receiver android:name=".ConnectionChangeReceiver"
          android:label="NetworkConnection">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter>
</receiver>

In my activity, I register the receiver:

ConnectionChangeReceiver receiver = new ConnectionChangeReceiver(); this.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

Now, I am confused as what to do next. When onReceive method is executed, how to make my activity aware of that? I know I could start a new activity, but that's not really what I want. Should I declare ConnectionChangeReceiver as a private class of my activity? Or is there any other solution?

Upvotes: 7

Views: 8081

Answers (2)

Rohit Singh
Rohit Singh

Reputation: 18202

Interface Approach!

You can communicate via an interface as well. This approach works even if your BroadcastReceiver is in a seperate file. You will not even have to access UI elements of Activity in the Broadcast.

Its pretty Straightforward. Just follow these 3 simple steps.

1) Create an interface

public interface MyListerner{

    public void performSomething(String arg);

} 

2) Initialize the Listener in ConnectionChangeReceiver

public class ConnectionChangeReceiver extends BroadcastReceiver {

      private MyListerner listener;

      @Override
      public void onReceive(Context context, Intent intent) {

            listener = (MyListerner )context;  // initialse

            ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
            if (activeNetInfo != null) {

              listener.performSomething("Some data");   // Call listener method
              
            } 
      }
}

3) Implement the interface and Override the method in your Activity

public class YourActivity implements MyListerner{
     
      // Activity relate stuff onCreate() etc 

     public void updateUI(String result){
         // Your code to update UI
     }

     @Override
     public void performSomething(String arg){
           updateUI(arg);
     }

}

Relevant Links: You can read in detail Why using an interface is a preferred approach in this case

Upvotes: 2

user658042
user658042

Reputation:

I think building the receiver as a private subclass of your activity is the way to go here. This way you can control events and data from your activity. Then you can just create one instance of it and register the receiver from code as you did above.

Note that you don't have to register your receiver in both the manifest and code. One of these is enugh - the manifest is basically a "static" registration while doing it in code allows dynamic registration at runtime. Also when you register in the manifest, a new instance of your receiver will automatically be created from the system, executed and terminated. Doing the reg in code allows to point to one specific instance.

Upvotes: 11

Related Questions