When the Android app needs to connect to the network, it does not connect to the network every time, so the program needs to detect the current device's network status in order to alert the user in a timely manner.
To determine the status of the network, you need to have the appropriate permission code as follows (Androidmanifest.xml):
?
| 12 |
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"><uses-permission android:name="android.permission.INTERNET"></uses-permission></uses-permission> |
Code to detect the current network status:
?
| 12345678910111213141516 |
public void checkNetworkState(Context context){ if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo(); //1.判断是否有网络连接 boolean networkAvailable = networkInfo.isAvailable(); //2.获取当前网络连接的类型信息 int networkType = networkInfo.getType(); if(ConnectivityManager.TYPE_WIFI == networkType){ //当前为wifi网络 }else if(ConnectivityManager.TYPE_MOBILE == networkType){ //当前为mobile网络 } }} |
A companion tour, a free dating site: www.jieberu.com
Push family, free tickets, scenic spots: www.tuituizu.com
Android Detects network connection status