可以观察网络状态吗?

时间:2011-07-01 08:53:29

标签: android android-networking

我想知道是否有办法以某种方式注册为网络访问的观察者(并且当互联网可用时运行一些回调函数),或者如果轮询是唯一的方法。谢谢!

1 个答案:

答案 0 :(得分:5)

您可以注册接收者:

//Callback  
private final BroadcastReceiver mNetworkStateReceiver = new BroadcastReceiver() {
    @Override
        public void onReceive(Context context, Intent intent) {
           //network state changes, you can process it, inforamtion in intent
        }
    };

//registering recievr in actibity or in service
IntentFilter mNetworkStateFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetworkStateReceiver , mNetworkStateFilter);

详细信息: http://developer.android.com/reference/android/net/ConnectivityManager.html