Steps for android to check the network connection status

Source: Internet
Author: User

To obtain network information, you must add the corresponding permissions to the AndroidManifest. xml file.
<Uses-permission android: name = "android. permission. ACCESS_NETWORK_STATE"/>
1) determine whether a network connection exists Copy codeThe Code is as follows: 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 the Wi-Fi network is available Copy codeThe Code is as follows: 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 Copy codeThe Code is as follows: 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) obtain the type of the current network connection Copy codeThe Code is as follows: 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 android applications, network access is required, and network status check is often required to provide users with necessary reminders. You can use ConnectivityManager to complete the job.
ConnectivityManager has four main tasks:
1. Listen to the network status of the mobile phone (including GPRS, WIFI, UMTS, etc)
2. Send a broadcast when the mobile phone status changes
3. failover when a network connection fails
4. Provide applications with high precision and rough states that can obtain Available Networks
To listen to the network status in a program, you only need to perform the following steps:
1. Define a Receiver to reload the onReceive function, and complete the required functions, such as changing the appearance of the Space Based on whether WIFI and GPRS are disconnected.Copy codeThe Code is as follows: 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 a handler in an appropriate place. You can register it in the program and call the following function in onCreate:
IntentFilter intentFilter = new IntentFilter ();
IntentFilter. addAction (ConnectivityManager. CONNECTIVITY_ACTION );
RegisterReceiver (connectionReceiver, intentFilter );
3. When appropriate, cancel the registration of the handler. You can cancel the registration in the program and call the following function in onDestroye:
If (connectionReceiver! = Null ){
UnregisterReceiver (connectionReceiver );
}
Ps: There are still many ways to use TelephonyManager on the Internet. The method is as follows (but I tried it several times and there are problems. For example, each time I enter an Activity for the first time, I will automatically receive a signal of network disconnection, when the network status changes, The system receives multiple callbacks and the status is incorrect. I don't know what to pay attention to. Please give me some advice !)Copy codeThe Code is as follows: final TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService (Context. TELEPHONY_SERVICE );
MTelephonyMgr. listen (new PhoneStateListener (){
@ Override
Public void onDataConnectionStateChanged (int state ){
Switch (state ){
Case TelephonyManager. DATA_DISCONNECTED: // The network is disconnected.
Break;
Case TelephonyManager. DATA_CONNECTING: // The network is being connected.
Break;
Case TelephonyManager. DATA_CONNECTED: // network connection
Break;
}
}
}, PhoneStateListener. LISTEN_DATA_CONNECTION_STATE );

As for the second method, I have not tried it. The first method is easy to use. If you want to hide the program in the background, you are advised to open a service and register BroadcastReceiver in the service, but do not forget to cancel the registration.
In the test, a route device connected to wifi is closed, but the program does not capture the unconnect network. It may be because the mobile phone device is connected to another route device immediately.
Android monitoring network status Copy codeThe Code is as follows: 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 used to determine whether the network is connected. "true" indicates that a network exists, and "false" indicates that no network exists. In Android network application development, it is often necessary to determine whether the network connection is available. Therefore, it is often necessary to listen to changes in the network status. For android network status monitoring, BroadcastReceiver can be used to receive broadcasting with network status changes. The specific implementation is as follows:Copy codeThe Code is as follows: @ Override
Public void onReceive (Context context, Intent intent ){
Log. e (TAG, "network status change ");
Boolean success = false;
// Obtain the 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 whether the Wi-Fi network is in use
Success = true;
}
State = connManager. getNetworkInfo (
ConnectivityManager. TYPE_MOBILE). getState (); // gets the network connection status
If (State. CONNECTED! = State) {// determine whether the GPRS network is being used
Success = true;
}
If (! Success ){
Toast. makeText (LocationMapActivity. this, "your network connection has been interrupted", Toast. LENGTH_LONG). show ();
}
}

Copy codeThe Code is as follows: // register a network listener
IntentFilter filter = new IntentFilter ();
Filter. addAction (ConnectivityManager. CONNECTIVITY_ACTION );
RegisterReceiver (mNetworkStateReceiver, filter );
// In onDestroy of Activity :'
UnregisterReceiver (mNetworkStateReceiver); // cancel the listener

In android development, many of my friends may determine the network type of the mobile phone, because the current android mobile phone may be in a 4-digit status.
1. No network (this status may be due to the shutdown of the mobile phone, the network is not enabled, and the signal is poor)
2. Use WIFI to access the Internet
3. CMWAP (China Mobile proxy)
4. access the Internet through CMNET
In these four statuses, if there is no network, you must be unable to request the Internet. If it is wap, you need to add a China Mobile proxy for your mobile phone. For more information, see Add a China Mobile proxy for your mobile phone!
The following are network judgment methods::Copy codeThe Code is as follows :/**
* @ Author sky
* Email vipa1888@163.com
* QQ: 840950105
* Obtain the current network status-1: No network 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 the service object is obtained, the network status is refreshed from time to time, so we only need to get the network status!
I hope to share my learning experience with you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.