android checks the network connection status implementation steps

  • 2020-05-07 20:26:22
  • OfStack

Getting network information requires adding the appropriate permissions in the AndroidManifest.xml file.
< uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" / >
1) determine if there is a network connection
 
public boolean isNetworkConnected(Context context) { 
if (context != null) { 
ConnectivityManager mConnectivityManager = (ConnectivityManager) context 
.getSystemService(Context.CONNECTIVITY_SERVICE); 
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); 
if (mNetworkInfo != null) { 
return mNetworkInfo.isAvailable(); 
} 
} 
return false; 
} 

2) determine whether WIFI network is available
 
public boolean isWifiConnected(Context context) { 
if (context != null) { 
ConnectivityManager mConnectivityManager = (ConnectivityManager) context 
.getSystemService(Context.CONNECTIVITY_SERVICE); 
NetworkInfo mWiFiNetworkInfo = mConnectivityManager 
.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
if (mWiFiNetworkInfo != null) { 
return mWiFiNetworkInfo.isAvailable(); 
} 
} 
return false; 
} 

3) determine whether the MOBILE network is available for
 
public boolean isMobileConnected(Context context) { 
if (context != null) { 
ConnectivityManager mConnectivityManager = (ConnectivityManager) context 
.getSystemService(Context.CONNECTIVITY_SERVICE); 
NetworkInfo mMobileNetworkInfo = mConnectivityManager 
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 
if (mMobileNetworkInfo != null) { 
return mMobileNetworkInfo.isAvailable(); 
} 
} 
return false; 
} 

4) gets information about the type of current network connection
 
public static int getConnectedType(Context context) { 
if (context != null) { 
ConnectivityManager mConnectivityManager = (ConnectivityManager) context 
.getSystemService(Context.CONNECTIVITY_SERVICE); 
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); 
if (mNetworkInfo != null && mNetworkInfo.isAvailable()) { 
return mNetworkInfo.getType(); 
} 
} 
return -1; 
} 

When developing an android application, network access is involved, and network status checks are often required to provide users with the necessary alerts. 1 this can generally be done with ConnectivityManager.
ConnectivityManager has four main tasks :
1. Monitor the mobile network status (including GPRS, WIFI, UMTS, etc.)
2. When the status of the mobile phone changes, send the broadcast
3, when a network connection fails to switch over
4. Provide applications with high precision and rough state of the available network
When we want to monitor the network status in the program, we only need to do the following steps:
1. Define one Receiver function to overload onReceive, and complete the required functions in it, such as changing the appearance of the space according to whether WIFI and GPRS are disconnected
 
connectionReceiver = new BroadcastReceiver() { 
@Override 
public void onReceive(Context context, Intent intent) { 
ConnectivityManager connectMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); 
NetworkInfo mobNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 
NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) { 
Log.i(TAG, "unconnect"); 
// unconnect network 
}else { 
// connect network 
} 
} 
}; 

2. Register Receiver in the appropriate place, which can be registered in the program. The following functions can be called in onCreate:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectionReceiver, intentFilter);
3. Cancel the registration of Receiver when appropriate, which can be cancelled in the program. The following function can be called in onDestroye:
if (connectionReceiver != null) {
unregisterReceiver(connectionReceiver);
}
Ps : there are many other ways to use TelephonyManager on the Internet. The methods are as follows (but I tried several times and had problems. For example, every time I entered an Activity for the first time, I automatically received a signal of network disconnection. Don't know what to pay attention to, for guidance!
 
final TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
mTelephonyMgr.listen(new PhoneStateListener(){ 
@Override 
public void onDataConnectionStateChanged(int state) { 
switch(state){ 
case TelephonyManager.DATA_DISCONNECTED:// Network disconnection  
break; 
case TelephonyManager.DATA_CONNECTING:// The network is connecting  
break; 
case TelephonyManager.DATA_CONNECTED:// On network connection  
break; 
} 
} 
}, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE); 

As for the second method, I have not tried it. The first way is still relatively easy to use, if you want to hide the program in the background, it is recommended to open an service, BroadcastReceiver registered in service, but do not forget to cancel the registration.
During the test, I encountered a situation where I shut down one of the routing devices currently connected to wifi, but the program did not capture unconnect network, possibly because the mobile device was immediately connected to another routing device
Android monitors network status
 
public static boolean isNetworkAvailable(Context context) { 
ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 
if (connectivity == null) { 
Log.i("NetWorkState", "Unavailabel"); 
return false; 
} else { 
NetworkInfo[] info = connectivity.getAllNetworkInfo(); 
if (info != null) { 
for (int i = 0; i < info.length; i++) { 
if (info[i].getState() == NetworkInfo.State.CONNECTED) { 
Log.i("NetWorkState", "Availabel"); 
return true; 
} 
} 
} 
} 
return false; 
} 

The above method is the code that determines whether the network is connected or not, and returns true for network and false for no network. In Android network application development, it is often necessary to determine whether a network connection is available, so it is often necessary to listen for changes in network state. The network status monitor of android can use BroadcastReceiver to receive the broadcast of network status change, which is implemented as follows
 
@Override 
public void onReceive(Context context, Intent intent) { 
Log.e(TAG, " Network state change "); 
boolean success = false; 
// Get network connection service  
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); 
// State state = connManager.getActiveNetworkInfo().getState(); 
State state = connManager.getNetworkInfo( 
ConnectivityManager.TYPE_WIFI).getState(); //  Gets the network connection status  
if (State.CONNECTED == state) { //  Determine if it is in use WIFI network  
success = true; 
} 
state = connManager.getNetworkInfo( 
ConnectivityManager.TYPE_MOBILE).getState(); //  Gets the network connection status  
if (State.CONNECTED != state) { //  Determine if it is in use GPRS network  
success = true; 
} 
if (!success) { 
Toast.makeText(LocationMapActivity.this, " Your network connection has been disconnected ", Toast.LENGTH_LONG).show(); 
} 
} 

 
// Register network monitor  
IntentFilter filter = new IntentFilter(); 
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 
registerReceiver(mNetworkStateReceiver, filter); 
// in Activity In the onDestroy In the :' 
unregisterReceiver(mNetworkStateReceiver); // Cancel to monitor  

Many friends will encounter mobile network type judgment in the development of android, because for the current android platform mobile phone: there may be 4 states
1. No network (this state may be caused by the shutdown of the mobile phone, the network is not on, the signal is bad, etc.)
2. Use WIFI to surf the Internet
3. CMWAP (China mobile agent)
4. CMNET surf the Internet
In these four states, if there is no network, it must be impossible to request Internet, if it is wap, it needs to add China mobile agent for the phone, about adding China mobile agent for the phone!
the following is the method of network judgment :
 
/** 
* @author sky 
* Email vipa1888@163.com 
* QQ:840950105 
*  Gets the current network state  -1 : no Internet  1 : WIFI network 2 : wap network 3 : net network  
* @param context 
* @return 
*/ 
public static int getAPNType(Context context){ 
int netType = -1; 
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
if(networkInfo==null){ 
return netType; 
} 
int nType = networkInfo.getType(); 
if(nType==ConnectivityManager.TYPE_MOBILE){ 
Log.e("networkInfo.getExtraInfo()", "networkInfo.getExtraInfo() is "+networkInfo.getExtraInfo()); 
if(networkInfo.getExtraInfo().toLowerCase().equals("cmnet")){ 
netType = CMNET; 
} 
else{ 
netType = CMWAP; 
} 
} 
else if(nType==ConnectivityManager.TYPE_WIFI){ 
netType = WIFI; 
} 
return netType; 
} 

Because what we get is the service object, so the network state is always refreshed, so we only need to get the network state can!
Learning lies in accumulation, hope to share with you 1

Related articles: