Detect Internet Connection Status (Android)

//Add below permissions in Manifest file <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> //add below file which contains logic to check Internet connection import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class ConnectionDetector{ private Context _context; public ConnectionDetector(Context context){ this._context = context; } public boolean isConnectingToInternet(){ ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) for (int i = 0; i < info.length; i++) if (info[i].getState() == NetworkInfo.State.CONNECTED) { Toast.makeText(context, "Internet is connected", Toast.LENGTH_SHORT).show(); return true; } } return false; } } //Now if you want to check Internet Connection in any of your application’s Activity then just call below method to check it out ConnectionDetector cd = new ConnectionDetector(getApplicationContext()); Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false /*Apart from this connected states, there are other states a network can achieve. They are listed below: Sr.No State 1 Connecting 2 Disconnected 3 Disconnecting 4 Suspended 5 Unknown */ //If you also get the type of connection connected then just add below code to above Java code file ConnectivityManager connMgr = (ConnectivityManager) myFragmentView.getContext() .getSystemService(Context.CONNECTIVITY_SERVICE);// change myFragmentView.getContext final NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); final NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if( wifi.isAvailable() ){ Toast.makeText(myFragmentView.getContext(), "Wifi enabled" , Toast.LENGTH_LONG).show(); } else if( mobile.isAvailable() ){ Toast.makeText(myFragmentView.getContext(), "Mobile 3G enabled" , Toast.LENGTH_LONG).show(); } else{ Toast.makeText(myFragmentView.getContext(), "No Network " , Toast.LENGTH_LONG).show();}
This snippet shows how to check the connection status.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.