38

我需要接收网络操作的广播,例如网络连接、断开连接等。我为此目的使用广播接收器。谁能告诉我我需要为网络事件捕获哪个意图操作,现在根据我在互联网上的搜索,我正在使用android.net.ConnectivityManager.CONNECTIVITY_ACTION

这是我的广播接收器类:

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..
    }
}
}

我还添加了访问网络状态的权限:

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

这是我在清单文件中声明此类的方式

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

如果我错了,或者如果有任何其他方法可以捕获网络事件,请建议我正确的意图操作。

4

2 回答 2

51

这是一个工作示例:

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

}
于 2010-02-19T09:03:43.173 回答
6

yanchenko 的回答非常有用,我只是稍微简化一下以获取连接状态,请修改 onReceive 如下:

public class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(ConnectivityReceiver.class.getSimpleName(), "action: "
                + intent.getAction());
        MyConstants.IS_NETWORK_AVAILABLE = haveNetworkConnection(context);
        //IS_NETWORK_AVAILABLE this variable in your activities to check networkavailability.

    } 


    private boolean haveNetworkConnection(Context context) {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager)   context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;    
    }
}
于 2012-10-05T11:39:07.223 回答