I'm developing an application in android which fetches data from the database. I have developed the code to find whether the WIFI or Mobile data is ON or OFF like this:
protected boolean isNetworkAvailable()
{
boolean connection=true;
ConnectivityManager connectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] activeNetworkInfo=connectivityManager.getAllNetworkInfo();
for(NetworkInfo ni:activeNetworkInfo)
{
if(ni.getTypeName().equalsIgnoreCase("WIFI"))
if(ni.isConnected())
haveConnectedWifi=true;
if(ni.getTypeName().equalsIgnoreCase("MOBILE"))
if(ni.isConnected())
haveConnectedMobile=true;
}
if(haveConnectedWifi==false && haveConnectedMobile==false)
{
connection=false;
}
return connection;
}
Now suppose that my WIFI or Mobile Data network is ON but I'm not connected to internet at all(WIFI not connected to any access point).How can i show this in android?
Thanks,
you can simply use this:
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null
// otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
This class is pretty complete :
public class ConnexionDetector extends BroadcastReceiver {
/**
* ATTRIBUTES
*/
private Context _context;
private boolean _noConnectivity;
private String _reason;
private boolean _isFailover;
private static boolean _isConnected = false;
private static boolean _isConnectivityGood = true;
public ConnexionDetector(Context context) {
this._context = context;
}
public void registerReceivers() {
_context.registerReceiver(this, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
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) {
return true;
}
}
return false;
}
public static NetworkInfo getNetworkInfo(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo();
}
public static boolean isConnected(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected());
}
public static boolean isConnectedWifi(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}
public static boolean isConnectedMobile(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}
public static boolean isConnectedFast(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected() && isConnectionFast(info.getType(), info.getSubtype()));
}
private static boolean isConnectionFast(int type, int subType) {
if (type == ConnectivityManager.TYPE_WIFI) {
return true;
}
else if (type == ConnectivityManager.TYPE_MOBILE) {
switch (subType) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_CDMA:
return false; // ~ 14-64 kbps
case TelephonyManager.NETWORK_TYPE_EDGE:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_0:
return true; // ~ 400-1000 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_A:
return true; // ~ 600-1400 kbps
case TelephonyManager.NETWORK_TYPE_GPRS:
return false; // ~ 100 kbps
case TelephonyManager.NETWORK_TYPE_HSDPA:
return true; // ~ 2-14 Mbps
case TelephonyManager.NETWORK_TYPE_HSPA:
return true; // ~ 700-1700 kbps
case TelephonyManager.NETWORK_TYPE_HSUPA:
return true; // ~ 1-23 Mbps
case TelephonyManager.NETWORK_TYPE_UMTS:
return true; // ~ 400-7000 kbps
case TelephonyManager.NETWORK_TYPE_UNKNOWN:
default:
return false;
}
}
else {
return false;
}
}
@Override
public void onReceive(Context context, Intent intent) {
_noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
_reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
_isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
//
if (_noConnectivity) {
_isConnected = false;
}
else {
if (isConnectedFast(_context)) {
_isConnectivityGood = true;
}
else {
_isConnectivityGood = false;
}
_isConnected = true;
}
}
}
Try this,
ConnectivityManager connec = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected()||mobile.isConnected())
return true;
else if (wifi.isConnected() && mobile.isConnected())
return true;
else
return false;
} catch (NullPointerException e) {
Log.d("ConStatus", "No Active Connection");
return false;
}
This code might help you.
ConnectivityManager cn= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cn.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
testwifi=networkInfo.isConnected();
if(!testwifi)
tv1.setText("wifi is off");
else
tv1.setText("wifi is on");
Try this:
public static void isNetworkAvailable(Context context){
HttpGet httpGet = new HttpGet("http://www.google.com");
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try{
Log.d(TAG, "Checking network connection...");
httpClient.execute(httpGet);
Log.d(TAG, "Connection OK");
return;
}
catch(ClientProtocolException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
Log.d(TAG, "Connection unavailable");
}
call the isConnectingToInternet function of this class to check the internet connection where u want to check internet connectivity .
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;
}
/**
* Checking for all possible internet providers
* **/
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) {
return true;
}
}
return false;
}
}
To ensure that actual internet is available or not need to ping any global url eg www.google.com
This will work 100%
public static boolean isNetwokReachable() {
final ConnectivityManager connMgr = (ConnectivityManager) mSmartAndroidActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Android Application");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(10 * 1000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
} else {
return false;
}
} catch (Throwable e) {
return false;
}
} else {
return false;
}
}
i was searching this question's answer also then i do this in my code and it works . don't know , it is good or not .if there is something wrong please tell me about that.
Step : 1 Make a BaseActivity class and extends AppCompatActivity class and write code in this for network check and show message to user if there is no network connection :
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkRequest
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
open class BaseActivity : AppCompatActivity() {
private var cManager: ConnectivityManager? = null
private var mCallback: ConnectivityManager.NetworkCallback? = null
private var request : NetworkRequest? = null
private var view: View? = null
private var mSnackBar: Snackbar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
cManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
request = NetworkRequest.Builder().build()
// get root view where we want to show message
view = window.decorView.rootView
mCallback = object : ConnectivityManager.NetworkCallback() {
override fun onLost(network: Network) {
super.onLost(network)
mSnackBar = Snackbar.make(view!!, "No Network connection", Snackbar.LENGTH_LONG)
mSnackBar!!.duration = Snackbar.LENGTH_INDEFINITE
mSnackBar!!.show()
}
override fun onAvailable(network: Network) {
super.onAvailable(network)
if (mSnackBar != null){
mSnackBar!!.dismiss()
}
}
}
cManager!!.registerNetworkCallback(request!!, mCallback!!)
}
override fun onStop() {
super.onStop()
cManager!!.unregisterNetworkCallback(mCallback!!)
}
}
Step 2:
Now in MainActivity class , extends this BaseActivity class.
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
step 3 : Don't forget to add this in AndroidManifest File
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
now run and check your application. :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.