In Android development, it is sometimes necessary to determine the current network connection status before making a network request. This article describes how to get the current network connection status of your Android device!
Required permissions (added in the Androidmanifest.xml file):
<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>
Java code (mainactivity.java file)
Package Com.example.androidtest;import Android.net.connectivitymanager;import Android.net.networkinfo;import Android.net.networkinfo.state;import Android.os.bundle;import Android.app.activity;import Android.content.Context Import Android.util.log;import Android.view.menu;public class Mainactivity extends Activity {@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Boolean bflag = Isnetworkavailable (This.getapplicationcontext ()), if (bflag) {log.i ("Network state-", "Connected");} else {log.i ("Network state-", "Disconnected");}} /** * Determine network connection Status * * @param CTX * @return */public boolean isnetworkavailable (Context ctx) {Boolean bflag = False;if (CTX!) = null) {Connectivitymanager conman = (Connectivitymanager) ctx.getsystemservice (Context.connectivity_service); Conman! = NULL) {//WiFi Networknetworkinfo ninfow = Conman.getnetworkinfo (Connectivitymanager.type_wifi); if (NInfoW! = N ull) {state WiFi = NinfOw.getstate (); if (state.connected = = WiFi) {bflag = true;}} if (!bflag) {//mobile Networknetworkinfo ninfom = Conman.getnetworkinfo (connectivitymanager.type_mobile); if (NInfoM! = NULL) {state mobile = ninfom.getstate (); if (state.connected = = Mobile) {bflag = true;}}}} return bflag;} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.activity_main, menu); return true;}}
Isnetworkavailable method First do WiFi connection status, if WiFi is not connected, then do 2g/3g/4g ... Mobile phone network connection status judgment.
Android devices determine network connection status