Android Network connection judgment and processing

Source: Internet
Author: User



Blog Category: Android

Obtaining network information requires that the appropriate permissions be added to the Androidmanifest.xml file.

<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>



1) Determine if there is an Internet connection


Press CTRL + C to copy the code
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;
}
Press CTRL + C to copy the code

2) determine if the WiFi network is available


Press CTRL + C to copy the code
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;
}
Press CTRL + C to copy the code



3) Determine if the mobile network is available


Press CTRL + C to copy the code
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;
}
Press CTRL + C to copy the code

4) Get the type information for the current network connection


Press CTRL + C to copy the code
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;
}
Press CTRL + C to copy the code



When developing an Android app, it involves network access, often requiring network status checks to provide users with the necessary reminders. This work can generally be done through Connectivitymanager.

Connectivitymanager has four main tasks:

1. Monitor mobile network status (including Gprs,wifi, UMTS, etc.)

2, when the mobile phone status changes, send broadcast

3. Failover when a network connection fails

4. Provide the application with a high-precision and coarse state that can obtain available networks

When we want to listen to the network status in the program, just a few steps:

1, define a receiver overloaded with the OnReceive function, in which to complete the required functions, such as based on WiFi and GPRS is disconnected to change the appearance of the space




Copy Code

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
}
}
};

Copy Code





2, register receiver in the appropriate place, you can register in the program, call the following function in OnCreate:



Intentfilter intentfilter = new Intentfilter ();
Intentfilter.addaction (connectivitymanager.connectivity_action);
Registerreceiver (Connectionreceiver, Intentfilter);





3, when appropriate to unregister receiver, can be canceled in the program, in the Ondestroye call the following function:



if (connectionreceiver! = null) {
Unregisterreceiver (Connectionreceiver);
}





Ps: There are a lot of ways to use Telephonymanager on the Internet, the method is as follows (but I have tried several times have problems, such as each time the first time into an activity will automatically receive the network disconnection signal, each time the network state changes to receive multiple callbacks and the status is incorrect. Do not know what to pay attention to the place, seek guidance! )
Copy Code

Final Telephonymanager mtelephonymgr = (telephonymanager) getsystemservice (Context.telephony_service);

Mtelephonymgr.listen (New Phonestatelistener () {

@Override

public void ondataconnectionstatechanged (int.) {

Switch (state) {

Case TELEPHONYMANAGER.DATA_DISCONNECTED://Network disconnection

Break

Case telephonymanager.data_connecting://Network is connecting

Break

Case telephonymanager.data_connected://on network connection

Break

}

}

}, Phonestatelistener.listen_data_connection_state);

Copy Code



As for the second method, I have not tried it. The first way is still relatively good, if you want to hide the program in the background, it is recommended to open a service, the Broadcastreceiver registered in the service, but do not forget to unregister.

In the test, a routing device that is currently connected to WiFi is turned off, but the program does not capture the Unconnect network, possibly because the mobile device is immediately connected to another routing device.


Android Monitor network status

Copy Code

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++) {
if (info[i].getstate () = = NetworkInfo.State.CONNECTED) {
LOG.I ("Networkstate", "Availabel");
return true;
13}
14}
15}
16}
-return false;
18}

Copy Code


HTML code

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 to determine whether the network connection code, return True indicates that there is a network, return false indicates no network. In the development of Android Web applications, it is often necessary to determine whether a network connection is available, so it is often important to listen for changes in network status. Android Network status monitoring can use Broadcastreceiver to receive network status changes broadcast, the implementation of the following:
Copy Code

1 @Override
2 public void OnReceive (context context, Intent Intent) {
3 LOG.E (TAG, "Network status change");
4
5 Boolean success = FALSE;
6
7//Get Network Connection Service
8 Connectivitymanager Connmanager = (connectivitymanager) getsystemservice (Connectivity_service);
9//state state = Connmanager.getactivenetworkinfo (). GetState ();
Ten state state = Connmanager.getnetworkinfo (
Connectivitymanager.type_wifi). GetState (); Get Network Connection Status
if (state.connected = = state) {//Determine if WiFi network is in use
Success = true;
14}
15
State = Connmanager.getnetworkinfo (
Connectivitymanager.type_mobile). GetState (); Get Network Connection Status
if (state.connected! = state) {//Determine if GPRS network is being used
Success = true;
20}
21st
if (!success) {
Toast.maketext (Locationmapactivity.this, "Your network connection has been interrupted", Toast.length_long). Show ();
24}
25
26}

Copy Code


In the OnCreate of activity:

Register for Network Monitoring
Intentfilter filter = new Intentfilter ();
Filter.addaction (connectivitymanager.connectivity_action);
Registerreceiver (mnetworkstatereceiver, filter);
In the OnDestroy of activity: '

Unregisterreceiver (Mnetworkstatereceiver); Cancel Monitoring

Many friends in the Android development, will encounter the phone network type judgment, because on the current Android platform phone: There may be 4 in the state

1. No network (this state may be due to phone downtime, network is not open, bad signal, etc.)

2. Use WiFi internet access

3.CMWAP (China Mobile agent)

4.CMNET Internet access

These four states, if there is no network, must not be able to request the Internet, if it is WAP need to add China Mobile agent for mobile phones, for mobile phones to add agents, please go to

Http://www.2cto.com/kf/201111/112100.html Here is an example of adding China Mobile agent!

Here's how the network is judged:
Copy Code

1/**
2
3 * @author Sky
4
5 * Email [email protected]
6
7 * qq:840950105
8
9 * Get current network status-1: No network 1:wifi network 2:wap Network 3:net Network
10
* @param context
12
* @return
14
15 */
16
public static int Getapntype (context context) {
18
NetType int =-1;
20
Connectivitymanager connmgr = (connectivitymanager) context.getsystemservice (Context.connectivity_service);
22
Networkinfo networkinfo = Connmgr.getactivenetworkinfo ();
24
25
26
if (networkinfo==null) {
28
return netType;
30
31}
32
NType int = Networkinfo.gettype ();
34
if (ntype==connectivitymanager.type_mobile) {
36
PNS log.e ("Networkinfo.getextrainfo ()", "Networkinfo.getextrainfo () is" +networkinfo.getextrainfo ());
38
if (Networkinfo.getextrainfo (). toLowerCase (). Equals ("Cmnet")) {
40
NetType = CMNET;
42
43}
44
else{
46
NetType = Cmwap;
48
49}
50
51}
52
Ntype==connectivitymanager.type_wifi else if () {
54
NetType = WIFI;
56
57}
58
NetType return;
60
61}

Copy Code

Because the access is the service object, so this network state is always refreshed, so we just need to get the network state on it!

Learning is to accumulate, hope to share with you

Reprint Address: http://www.cnblogs.com/qingblog/archive/2012/07/19/2598983.html

Android Network connection judgment and processing

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.