使用ConnectivityManager监听网络状态变化

	mIntenFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    mConnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    mReceiver = new BroadcastReceiver() {
			
		@Override
		public void onReceive(Context context, Intent intent) {

			if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
				Log.i(TAG, "netWork has lost");
			}
		
			NetworkInfo tmpInfo = (NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
			Log.i(TAG, tmpInfo.toString() + " {isConnected = " + tmpInfo.isConnected() + "}");
		}
	};


注册Receiver,监听网络变化:
registerReceiver(mReceiver, mIntenFilter);


取消注册,不再监听网络变化:
unregisterReceiver(mReceiver);



也可在AndroidManifest.xml中注册BroadcastReceiver
        <receiver android:name=".ConnectionReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>	


程序第一次启动时会收到一个Broadcast

从 GPRS 到 WIFI,程序至少会收到3个Broadcast
第一个是连接到WIFI
第二个是断开GPRS
第三个是连接到WIFI

从WIFI到GPRS,程序至少会收到2个Broadcast
第一个是断开Wifi
第二个是连接到GPRS


你可能感兴趣的:(使用ConnectivityManager监听网络状态变化)