Determine whether a network exists

Source: Internet
Author: User

Steps:

1. Get the connectivitymanager object

Context context = activity. getapplicationcontext (); // obtain all connection management objects of the mobile phone (including management of Wi-Fi, net, and other connections) connectivitymanager = (connectivitymanager) context. getsystemservice (context. connectivity_service );

2. Get the networkinfo object

// Obtain the networkinfo object networkinfo [] networkinfo = connectivitymanager. getallnetworkinfo ();

3. Determine whether the current network status is in the connection status

if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED){      return true;}

4. Add the permission to access the current network status in androidmanifest. xml.

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

 

// -------------- Specific code :--------------------------------------------

Package com. example. wangluo;

Import android.net. connectivitymanager;
Import android.net. networkinfo;
Import Android. OS. Bundle;
Import Android. App. activity;
Import Android. content. context;
Import Android. View. Menu;
Import Android. widget. Toast;

Public class mainactivity extends activity {

@ Override
Protected void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. activity_main );

If (isnetworkavailable (mainactivity. This )){
Toast. maketext (this, "the current network is available! ", 0). Show ();
} Else {
Toast. maketext (this, "No network is available now !!! ", 0). Show ();
}

}
/**
* Check whether the current network is available
* @ Param Activity
* @ Return
*/

Public Boolean isnetworkavailable (activity ){
// Obtain the context
Context context = activity. getapplicationcontext ();
// Obtain all connection management objects (including management of Wi-Fi and net connections) of the mobile phone. The connectivity manager obtains system services through context.
Connectivitymanager = (connectivitymanager) Context. getsystemservice (context. connectivity_service );
// Determines whether the connectivity manager is empty. If it is empty, return
If (connectivitymanager = NULL ){
Return false;
} Else {
// Obtain all network information through the connectivity Manager
Networkinfo [] networkinfos = connectivitymanager. getallnetworkinfo ();
// Determine whether the network information is not empty and the number of network information is greater than 0
If (networkinfos! = NULL & networkinfos. length> 0 ){
// Traverse Network Information
For (INT I = 0; I <networkinfos. length; I ++ ){
System. Out. println (I + "= status =" + networkinfos [I]. getstate ());
System. Out. println (I + "= type =" + networkinfos [I]. gettypename ());
// Determine whether the current network status is in the connection status
If (networkinfos [I]. getstate () = networkinfo. state. Connected)
{
Return true;
}
}
}
}


Return false;

}



}

 

 

 

 

 

 

//-------------------------------------------------------------------

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 the Code as follows:
Public Boolean isnetworkconnected (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 the Code as follows:
Public Boolean iswificonnected (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 the Code as follows:
Public Boolean ismobileconnected (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 the Code as follows:
Public static int getconnectedtype (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 the Code as follows:
Connectionreceiver = new broadcastreceiver (){
@ Override
Public void onreceive (context, 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:

Copy the Code as follows:
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:

Copy the Code as follows:
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 the 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: // 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

Copy the Code as follows:
Public static Boolean isnetworkavailable (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 broadcast requests with network status changes. The specific implementation is as follows:

Copy the Code as follows:
@ Override
Public void onreceive (context, intent ){
Log. E (TAG, "network status change ");
Boolean success = false;
// Obtain the Network Connection Service
Connectivitymanager connmanager = (connectivitymanager) getsystemservice (connectivity_service );
// 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 the Code 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
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
The following are network judgment methods::

Copy the Code as follows:
/**
* @ Author sky
* Email [email protected]
* 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 ){
Int nettype =-1;
Connectivitymanager connmgr = (connectivitymanager) Context. getsystemservice (context. connectivity_service );
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!

Determine whether a network exists

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.