Android杂谈之网络实时监测

Android监测网络状态分四步步进行


1.定义一个广播接收者

private BroadcastReceiver myNetReceiver = new BroadcastReceiver() { 
        
        @Override 
        public void onReceive(Context context, Intent intent) { 
            
         String action = intent.getAction(); 
               if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { 
                     
                   mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 
                   netInfo = mConnectivityManager.getActiveNetworkInfo(); 
                   TextView networkState = (TextView) MainActivity.this.findViewById(R.id.network_state);
                   if(netInfo != null && netInfo.isAvailable()) {  
                        
                       String name = netInfo.getTypeName();  
                       if(netInfo.getType()==ConnectivityManager.TYPE_WIFI || netInfo.getType()==ConnectivityManager.TYPE_ETHERNET || netInfo.getType()==ConnectivityManager.TYPE_MOBILE){ 
                    	 //网络连接 ,隐藏控件
                    	 networkState.setVisibility(View.GONE);
                       } 
                     } else { 
                         //网络断开  ,显示控件 
                    	 networkState.setVisibility(View.VISIBLE);
                   } 
               } 
          
          }  
   };  

2.重写onDestroy(),在Activity销毁时注销广播

@Override
    public void onDestroy() { 
        super.onDestroy();
        //注销广播
        if(myNetReceiver!=null){ 
               unregisterReceiver(myNetReceiver); 
        }
    }


3.在onCreate方法中注册广播

//注册广播
		IntentFilter mFilter = new IntentFilter();
		mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(myNetReceiver, mFilter);

最后别忘了配置权限

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



你可能感兴趣的:(android,NetWork,state)