There are currently available networks, such as:
There are currently no networks available, such as:
Implementation steps:
1. Get Connectivitymanager Object
Context context = Activity.getapplicationcontext ();//Get phone All connection management objects (including management of connections such as Wi-fi,net) Connectivitymanager Connectivitymanager = (Connectivitymanager) context.getsystemservice (Context.connectivity_service);
2. Get Networkinfo Object
Get Networkinfo object networkinfo[] Networkinfo = Connectivitymanager.getallnetworkinfo ();
3, determine whether the current network status is connected state
if (networkinfo[i].getstate () = = NetworkInfo.State.CONNECTED) { return true;}
4. Add access to the current network state permission 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 (), "Currently available network! ", Toast.length_long). Show (); } else {Toast.maketext (getapplicationcontext), "There is currently no network available!" ", Toast.length_long). Show (); }}/** * Check if the current network is available * * @param context * @return */public Boolean Isnetworkavailab Le (activity activity) {Context context = Activity.getapplicationcontext (); Get phone all connection management objects (including management of connections such as wi-fi,net) Connectivitymanager Connectivitymanager = (connectivitymanager) context.getsyst Emservice (Context.connectivity_service); if (Connectivitymanager = = null) {return false; } else {//Get NetwoRkinfo Object networkinfo[] Networkinfo = Connectivitymanager.getallnetworkinfo (); if (networkinfo! = null && networkinfo.length > 0) {for (int i = 0; i < Networkin Fo.length; i++) {System.out.println (i + "= = = Status = = =" + networkinfo[i].getstate ()); System.out.println (i + = = = = = = = = = + Networkinfo[i].gettypename ()); Determines whether the current network state is a connection state if (networkinfo[i].getstate () = = NetworkInfo.State.CONNECTED) { return true; }}}} return false; }}
Results from the console printout:
Determine if the current network is available in Android