5

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...

M.V.
  • 1,662
  • 8
  • 32
  • 55
  • 2
    Use the method you just mentioned to test if there's internet availability. If there isn't, simply show an AlertDialog and don't try connecting? Not to mention that Socket communication (if that is what you use) should be in try/catch clauses, which means you can simply catch the exceptions. I don't see the problem. – Codemonkey May 06 '11 at 12:33

6 Answers6

36
 /**
   * 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;
  }
peceps
  • 17,370
  • 11
  • 72
  • 79
  • 1
    On the HTC Desire running 2.2.2 there's a bug where getActiveNetworkInfo() always returns null. This code is great because it still works and only falls back to getActiveNetworkInfo() if it needs to. – Kieran Apr 12 '12 at 02:32
  • 1
    +1 for being most bulletproof example I have found for checking network connectivity – alice_silver_man Apr 19 '13 at 20:01
4

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();
}
Nikola K.
  • 7,093
  • 13
  • 31
  • 39
MByD
  • 135,866
  • 28
  • 264
  • 277
  • But when I get this... how can I than just show the message telling No connection available and stop executing the other things: – M.V. May 06 '11 at 12:42
  • @M.V. - See edited answer in a minute – MByD May 06 '11 at 12:43
  • Thanks, but do I have to put in all Activities or is it enough to put it just in main Activity? – M.V. May 06 '11 at 15:58
  • I don't know the structure of your application, so it's hard to say, but either put it in places where you access the web or if you have one class that handles the connection and returns some string, put it there. – MByD May 06 '11 at 16:01
3

I can't make comment but note that NetworkInfo.isConnectedOrConnecting(); in all the above answers will only tell you if you are connected to router or not but if you are connected to router that don't have internet access then your application will crash because it will through UnknownHostException.
you should add the following catch enclose to your try catch

catch (UnknownHostException e) {
    getRequest.abort();
    Log.w("unknownhostexception whicle connects to the host " + url, e);
    }

or make timeout for your request what ever you want.

Amal
  • 971
  • 9
  • 25
1

For this you need to have following permission in your manifest.

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Sandeep
  • 1,814
  • 21
  • 25
0
private boolean connectionAvailable() {
    boolean connected = false;
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
        //we are connected to a network
        connected = true;
    }
    return connected;
}
Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
0
ConnectivityManager conMgr  = ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 
 NetworkInfo info = conMgr.getActiveNetworkInfo(); 

if(info != null && info.isConnected()) 
{
   // internet is there.
}
else
{
   // internet is not there.
}
Manish Dubey
  • 4,206
  • 8
  • 36
  • 65
Sumant
  • 2,775
  • 2
  • 22
  • 30