Determine if network connectivity is available and monitor network status in Android

Source: Internet
Author: User

Determine if the network connection is available and monitor network status in Android font: [Increase decrease] type: Reprint to obtain the network information need to add the appropriate permissions in the Androidmanifest.xml file, the next detail on the Android to determine whether the network connection is available and monitor network status , interested friends can refer to the following

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

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 if the WiFi 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 if 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) Get the type information for 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 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 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 receiver in the appropriate place, you can register in the program, call the following function in OnCreate:

Copy CodeThe code is as follows:
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:

Copy CodeThe code is as follows:
if (connectionreceiver! = null) {
Unregisterreceiver (Connectionreceiver);
}


Ps: There are a lot of ways to use Telephonymanager on the Internet, as follows (but I've tried several times and I've had problems, such as automatically receiving a signal that the network is disconnected each time I enter an activity for the first time. Multiple callbacks are received each time the network status changes and the status is incorrect. Do not know what to pay attention to the place, seek guidance! )

Copy CodeThe code is as follows:
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);


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 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 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 CodeThe code is as follows:
@Override
public void OnReceive (context context, Intent Intent) {
LOG.E (TAG, "Network status change");
Boolean success = false;
Access to network connectivity services
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 in use
Success = true;
}
State = Connmanager.getnetworkinfo (
Connectivitymanager.type_mobile). GetState (); Get Network Connection Status
if (state.connected! = state) {//Determine if 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 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
Here's how the network is judged :

Copy CodeThe code is as follows:


/**
* @author Sky
* Email [email protected]
* qq:840950105
* Get 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;
}

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.