Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android communicate between activity and broadcast receiver

Tags:

People also ask

How do you communicate between activity and service?

This example demonstrates how do I communicate between Activity and Service in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How can I communicate between two services in Android?

You have to use BroadcastReceiver to receive intents, and when you want to communicate simply make an Intent with appropriate values. This way you should be able to make a 2-way communication between any component.

How do you share data between activity and service?

Primitive Data Types To share primitive data between Activities/Services in an application, use Intent. putExtras(). For passing primitive data that needs to persist use the Preferences storage mechanism. The android.


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?