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

	
            
                
            
        

要读取网络状态记得要加权限


 

 

 

 

 

 

你可能感兴趣的:(移动开发,android开发)