views:

1358

answers:

1

Hi..

I am need to receive broadcast for network actions like network connected, disconnected etc. I am using a broadcast receiver for the purpose. Can any 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">
</uses-permission>

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 right intent action if I am wrong OR if there is any other way to catch network events.

+3  A: 

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());
    }

}
alex