[小代码]监听wifi, 3g的开、关

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            boolean isWifiConnected = false;
            boolean isMobileConnected = false;

            ConnectivityManager connMgr = (ConnectivityManager) 
                    context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if(networkInfo != null)
            isWifiConnected = networkInfo.isConnected();

            networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if(networkInfo != null)
            isMobileConnected = networkInfo.isConnected();      

            Log.d("network status", "wifi == " + isWifiConnected + " and mobile == " + isMobileConnected);

        }
    };

注册监听:

registerReceiver(mConnReceiver, 
           new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

manifest:

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

你可能感兴趣的:(android,监听,3G,Wi-Fi)