在android sdk中的networking事件的意图行动
我需要接收networking行为,如networking连接,断开等广播。我正在使用广播接收机为此目的。 任何人都可以告诉我,我需要为networking事件捕获哪些意图行动,现在按照我在互联网上的search我使用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.. } } }
而且我还添加了访问networking状态的权限:
<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>
如果我错了,请告诉我正确的意向操作,或者是否有其他方法来捕捉networking事件。
这是一个工作的例子:
<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()); } }
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; } }