Intent action for network events in android sdk

mudit picture mudit · Feb 19, 2010 · Viewed 38.9k times · Source

I need to receive broadcasts for network actions like network connected, disconnected etc. I am using a broadcast receiver for this purpose. Can anyone please tell me which intent action I need to capture for network events, right now as per my search on internet I am using android.net.ConnectivityManager.CONNECTIVITY_ACTION.

Here is my broadcast receiver class:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class NetworkStateReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub


    if (intent.getAction().equals(
            android.net.ConnectivityManager.CONNECTIVITY_ACTION)) {

        // do something..
    }
}
}

and I have also added permission for accessing network state:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

here is how I have declared this class in manifest file

<receiver class=".NetworkStateReceiver" android:name=".NetworkStateReceiver">
    <intent-filter>
            <action android:name="android.net.ConnectivityManager.CONNECTIVITY_ACTION" />
    </intent-filter>
</receiver>

Please suggest me the right intent action if I am wrong OR if there is any other way to catch network events.

Answer

yanchenko picture yanchenko · Feb 19, 2010

Here's a working example:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

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

.

public class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(ConnectivityReceiver.class.getSimpleName(), "action: "
                + intent.getAction());
    }

}