Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check internet connection in ANDROID [duplicate]

Hello I have application based on data retrieved over internet...

How can I handle my app in case there is no connection available?

I can detect connection with

ConnectivityManager cm = (ConnectivityManager) 
getSystemService(this.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();

It works fine... But how can I prevent Force Erros when I know there is no connection? I would like a message to be shown - something like: "Sorry! There is no internet connection available!" and not my application to crush...

like image 674
M.V. Avatar asked May 06 '11 12:05

M.V.


People also ask

How do you check internet is on or not in android programmatically?

In android, we can determine the internet connection status easily by using getActiveNetworkInfo() method of ConnectivityManager object. Following is the code snippet of using the ConnectivityManager class to know whether the internet connection is available or not.


2 Answers

 /**
   * Checks if the device has Internet connection.
   * 
   * @return <code>true</code> if the phone is connected to the Internet.
   */
  public static boolean hasConnection() {
    ConnectivityManager cm = (ConnectivityManager) MbridgeApp.getContext().getSystemService(
        Context.CONNECTIVITY_SERVICE);

    NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
      return true;
    }

    NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobileNetwork != null && mobileNetwork.isConnected()) {
      return true;
    }

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
      return true;
    }

    return false;
  }
like image 93
peceps Avatar answered Nov 10 '22 00:11

peceps


getActiveNetworkInfo() may return null, so you will get a force close, but you can do that:

ConnectivityManager cm = (ConnectivityManager) 
getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (null == ni)
    return false;
return ni.isConnectedOrConnecting();

Then the check is simple:

if (networkAvailable()) // << your method from above
{
// Do stuff
}
else
{
   Toast.makeToast(yourcontext, "No network available", Toast.LENGTH_LONG).show();
}
like image 42
MByD Avatar answered Nov 09 '22 22:11

MByD