android communicate between activity and broadcast receiver

亡梦爱人 提交于 2019-12-01 20:10:44

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/6882476/android-communicate-between-activity-and-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!