Determine whether network connections are available and monitor network status in Android

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

Getting network information requires adding permissions to 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 MOBILE network is available

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 by 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 function 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, such as the following. (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 better, if you want to hide the program in the background, it is recommended to open service, BroadcastReceiver registered in service, but don't forget to unregister.
In the test, I encountered such a situation that I shut down one of the routing devices currently connected to wifi, but the program did not capture unconnect network, probably because the mobile device 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, returning 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 monitoring of android can use BroadcastReceiver to receive the broadcast of network status change. The specific implementation is 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(); 
} 
}


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; 
}
0
Many friends will encounter mobile network type judgment in the development of android, because as far as the current android platform mobile phone is concerned, 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, Internet cannot be requested. If it is wap, China mobile agent needs to be added to the phone. For adding China mobile agent to the phone, please go to
here's how to make network judgments :

/** 
* @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: