Application Scenario: determine whether the current network is available
There are available networks, such:
There is no available network, such:
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>
The Code is as follows:
Public class classtestdemoactivity extends activity {@ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); If (isnetworkavailable (classtestdemoactivity. this) {toast. maketext (getapplicationcontext (), "the current network is available! ", Toast. length_long). Show ();} else {toast. maketext (getapplicationcontext ()," No network available currently! ", Toast. length_long ). show () ;}}/*** check whether the current network is available ** @ Param context * @ return */Public Boolean isnetworkavailable (activity) {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); If (connectivitymanager = NULL) {return false;} else {// Obtain the networkinfo object networkinfo [] networkinfo = connectivitymanager. getallnetworkinfo (); If (networkinfo! = NULL & networkinfo. length> 0) {for (INT I = 0; I <networkinfo. length; I ++) {system. out. println (I + "====" + networkinfo [I]. getstate (); system. out. println (I + "= type =" + networkinfo [I]. gettypename (); // determines whether the current network status is in the connection status if (networkinfo [I]. getstate () = networkinfo. state. connected) {return true ;}}} return false ;}}
Result printed on the console: