Android to determine if network connectivity is available and monitor network status _android

Source: Internet
Author: User

Obtaining network information requires the appropriate permissions to be added to the Androidmanifest.xml file.
<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>
1) To determine whether there is a network connection

Copy Code code 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 if WiFi network is available
Copy Code code 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 if mobile network is available
Copy Code code 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) Get the type information of the current network connection
Copy Code code 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, it involves network access, often requiring network state checks to provide users with the necessary reminders. It is generally possible to complete the work by Connectivitymanager.
Connectivitymanager has four main tasks
1, monitor the status of mobile phone network (including Gprs,wifi, UMTS, etc.)
2, mobile phone status change, send broadcast
3, when a network connection fails to failover
4. Provide applications with high precision and rough state of access to available networks
When we want to listen to the state of the network in the program, just a few steps:
1, define a receiver overload of 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 code 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, in the appropriate place to register receiver, you can register in the program, in OnCreate call the following functions can be:
Copy Code code as follows:

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

3, cancel the registration receiver when appropriate, can cancel in the program, call the following function in Ondestroye:
Copy Code code as follows:

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

Ps: There are a lot of ways to use Telephonymanager on the Internet, as follows (but I have tried several times to have problems, such as the first time you enter an activity will automatically receive the signal of network disconnect, each time the network state changes to receive multiple callbacks and the state is not correct.) Do not know what to pay attention to the place, seek advice! )
Copy Code code 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://Network disconnected
Break
Case telephonymanager.data_connecting://Network is connecting
Break
Case TELEPHONYMANAGER.DATA_CONNECTED://Network Connection
Break
}
}
}, Phonestatelistener.listen_data_connection_state);

As for the second method, I have not tried. The first way is still relatively easy to use, if you want to program hidden in the background, it is recommended to open a service, will broadcastreceiver registered in the service, but do not forget to cancel the registration.
In the test, it was possible to shut down a routing device that is currently connected to WiFi, but the program did not capture Unconnect network, possibly because the device immediately connected to another routing device.
Android Monitor network status
Copy Code code 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 to determine whether the network is connected to the code, return true to indicate a network, return false indicates no network. In the development of Android Web applications, it is often necessary to monitor the changes in network status to determine whether the network connection is available. Android's network state Monitor can use Broadcastreceiver to receive network state change broadcast, specifically implemented as follows:
Copy Code code as follows:

@Override
public void OnReceive (context context, Intent Intent) {
LOG.E (TAG, "Network state Change");
Boolean success = false;
Get a network connection service
Connectivitymanager Connmanager = (connectivitymanager) getsystemservice (Connectivity_service);
state state = Connmanager.getactivenetworkinfo (). GetState ();
state state = Connmanager.getnetworkinfo (
Connectivitymanager.type_wifi). GetState (); Get Network Connection Status
if (state.connected = = state) {//Determine if WiFi network is being used
Success = true;
}
State = Connmanager.getnetworkinfo (
Connectivitymanager.type_mobile). GetState (); Get Network Connection Status
if (state.connected!= state) {//To determine if GPRS network is being used
Success = true;
}
if (!success) {
Toast.maketext (Locationmapactivity.this, "Your network is disconnected", Toast.length_long). Show ();
}
}

Copy Code code as follows:

Registering for network monitoring
Intentfilter filter = new Intentfilter ();
Filter.addaction (connectivitymanager.connectivity_action);
Registerreceiver (mnetworkstatereceiver, filter);
In the OnDestroy of activity: '
Unregisterreceiver (Mnetworkstatereceiver); Cancel Listening

Many friends in the Android development, will encounter the type of mobile phone network judgment, because of the current Android platform mobile phone: There may be 4 of the state
1. No network (this state may be due to phone downtime, the network is not open, bad signals, etc.)
2. Use WiFi access
3.CMWAP (China Mobile agent)
4.CMNET Internet access
These four states, if there is no network, must be unable to request the Internet, if it is WAP need to add China Mobile agent for mobile phones, for mobile phone to add China Mobile agent, please to
Here's how the network is judged.
Copy Code code as follows:

/**
* @author Sky
* Email vipa1888@163.com
* qq:840950105 br>* get Current network status-1: No network 1:wifi network 2:wap Network 3:net Network
* @param context
* @return
*/
public static int Geta Pntype (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 get the service object, so this network state is always refreshed, so we just need to get the network status on it!
Learning is accumulating, and I hope to share it 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.