Android Network Connection judgment and handling

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

 


1 public boolean isNetworkConnected (Context context ){
2 if (context! = Null ){
3 ConnectivityManager mConnectivityManager = (ConnectivityManager) context
4. getSystemService (Context. CONNECTIVITY_SERVICE );
5 NetworkInfo mNetworkInfo = mConnectivityManager. getActiveNetworkInfo ();
6 if (mNetworkInfo! = Null ){
7 return mNetworkInfo. isAvailable ();
8}
9}
10 return false;
11}

2) Determine whether the Wi-Fi network is available

 


1 public boolean isWifiConnected (Context context ){
2 if (context! = Null ){
3 ConnectivityManager mConnectivityManager = (ConnectivityManager) context
4. getSystemService (Context. CONNECTIVITY_SERVICE );
5 NetworkInfo mWiFiNetworkInfo = mConnectivityManager
6. getNetworkInfo (ConnectivityManager. TYPE_WIFI );
7 if (mWiFiNetworkInfo! = Null ){
8 return mWiFiNetworkInfo. isAvailable ();
9}
10}
11 return false;
12}

 

3) Determine whether the MOBILE network is available

 


1 public boolean isMobileConnected (Context context ){
2 if (context! = Null ){
3 ConnectivityManager mConnectivityManager = (ConnectivityManager) context
4. getSystemService (Context. CONNECTIVITY_SERVICE );
5 NetworkInfo mMobileNetworkInfo = mConnectivityManager
6. getNetworkInfo (ConnectivityManager. TYPE_MOBILE );
7 if (mMobileNetworkInfo! = Null ){
8 return mMobileNetworkInfo. isAvailable ();
9}
10}
11 return false;
12}

4) obtain the type of the current network connection

 


1 public static int getConnectedType (Context context ){
2 if (context! = Null ){
3 ConnectivityManager mConnectivityManager = (ConnectivityManager) context
4. getSystemService (Context. CONNECTIVITY_SERVICE );
5 NetworkInfo mNetworkInfo = mConnectivityManager. getActiveNetworkInfo ();
6 if (mNetworkInfo! = Null & mNetworkInfo. isAvailable ()){
7 return mNetworkInfo. getType ();
8}
9}
10 return-1;
11}

 

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.

 

 


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 methods for using 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 !)


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. This may be because the mobile phone device is connected to another route device immediately.

 

Android monitoring network status
 

1 public static boolean isNetworkAvailable (Context context ){
2 ConnectivityManager connectivity = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE );
3 if (connectivity = null ){
4 Log. I ("NetWorkState", "Unavailabel ");
5 return false;
6} else {
7 NetworkInfo [] info = connectivity. getAllNetworkInfo ();
8 if (info! = Null ){
9 for (int I = 0; I <info. length; I ++ ){
10 if (info [I]. getState () = NetworkInfo. State. CONNECTED ){
11 Log. I ("NetWorkState", "Availabel ");
12 return true;
13}
14}
15}
16}
17 return false;
18}


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 broadcast requests with network status changes. The specific implementation is as follows:


1 @ Override
2 public void onReceive (Context context, Intent intent ){
3 Log. e (TAG, "network status change ");
4
5 boolean success = false;
6
7 // obtain the Network Connection Service
8 ConnectivityManager connManager = (ConnectivityManager) getSystemService (CONNECTIVITY_SERVICE );
9 // State state = connManager. getActiveNetworkInfo (). getState ();
10 State state = connManager. getNetworkInfo (
11 ConnectivityManager. TYPE_WIFI). getState (); // gets the network connection status
12 if (State. CONNECTED = state) {// determine whether the Wi-Fi network is in use
13 success = true;
14}
15
16 state = connManager. getNetworkInfo (
17 ConnectivityManager. TYPE_MOBILE). getState (); // gets the network connection status
18 if (State. CONNECTED! = State) {// determine whether the GPRS network is being used
19 success = true;
20}
21
22 if (! Success ){
23 Toast. makeText (LocationMapActivity. this, "your network connection has been interrupted", Toast. LENGTH_LONG). show ();
24}
25
26}


In onCreate of Activity:


// 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

If there is no network in these four statuses, 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 details about adding a China Mobile proxy for your mobile phone, please go

Http://www.bkjia.com/kf/201111/112100.html here write an example about adding China Mobile Agent!

The following is a network judgment method:


1 /**
2
3 * @ author sky
4
5 * Email vipa1888@163.com
6
7 * QQ: 840950105
8
9 * Get the current network status-1: No network 1: WIFI network 2: wap network 3: net network
10
11 * @ param context
12
13 * @ return
14
15 */
16
17 public static int getAPNType (Context context ){
18
19 int netType =-1;
20
21 ConnectivityManager connMgr = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE );
22
23 NetworkInfo networkInfo = connMgr. getActiveNetworkInfo ();
24
25
26
27 if (networkInfo = null ){
28
29 return netType;
30
31}
32
33 int nType = networkInfo. getType ();
34
35 if (nType = ConnectivityManager. TYPE_MOBILE ){
36
37 Log. e ("networkInfo. getExtraInfo ()", "networkInfo. getExtraInfo () is" + networkInfo. getExtraInfo ());
38
39 if (networkInfo. getExtraInfo (). toLowerCase (). equals ("cmnet ")){
40
41 netType = CMNET;
42
43}
44
45 else {
46
47 netType = CMWAP;
48
49}
50
51}
52
53 else if (nType = ConnectivityManager. TYPE_WIFI ){
54
55 netType = WIFI;
56
57}
58
59 return netType;
60
61}

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.

Related Article

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.