android 监听网络连接状态的改变

BroadcastReceiver

public class MyReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		//Toast.makeText(context, intent.getAction(), 1).show();
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo activeInfo = manager.getActiveNetworkInfo();
		Toast.makeText(context, "mobile:"+mobileInfo.isConnected()+"\n"+"wifi:"+wifiInfo.isConnected()
				        +"\n"+"active:"+activeInfo.getTypeName(), 1).show();
	}  //如果无网络连接activeInfo为null

}

在清单文件中注册 BroadcastReceiver

	<receiver android:name=".MyReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>

要读取网络状态记得要加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

出自:http://blog.csdn.net/centralperk/article/details/7597516

你可能感兴趣的:(android 监听网络连接状态的改变)