0

Possible Duplicate:
Android - detect whether there is an Internet connection available
How to check network connection enable or disable in WIFI and 3G(data plan) in mobile?

In my cell when I run my app then this application is crashed because net connection is not there.so how to give the message that the connection is not there like. or on your wif

please help me

thank you

Community
  • 1
  • 1
user1061793
  • 1,047
  • 8
  • 19
  • 27

2 Answers2

2

See below code.

ConnectivityManager conMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    // ARE WE CONNECTED TO THE NET
    if (conMgr.getActiveNetworkInfo() != null
            && conMgr.getActiveNetworkInfo().isAvailable()
            && conMgr.getActiveNetworkInfo().isConnected()) {
        return true;

        // internet connection is wroking
    } else {
        return false;
        // internet connection is not wroking
    }
Dhaval Khant
  • 2,467
  • 2
  • 16
  • 24
0

Use this method in your Activity and call this when you want to know whether the net is available or not.

public boolean isInternetOn(Context ctx) {
    this.mContext = ctx;
    ConnectivityManager Connect_Manager = (ConnectivityManager) mContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    State connected = NetworkInfo.State.CONNECTED;
    State connecting = NetworkInfo.State.CONNECTING;
    State disconnected = NetworkInfo.State.DISCONNECTED;

    State info0 = Connect_Manager.getNetworkInfo(0).getState();
    State info1 = Connect_Manager.getNetworkInfo(1).getState();

    // ARE WE CONNECTED TO THE NET
    if (info0 == connected || info0 == connecting || info1 == connecting
            || info1 == connected) {

        // MESSAGE TO SCREEN FOR TESTING (IF REQ)
        // Toast.makeText(this, connectionType + " connected",
        // Toast.LENGTH_SHORT).show();
        Log.d("Internet", "Connected");
        return true;
    } else if (info0 == disconnected || info1 == disconnected) {
        Log.d("Internet", "DisConnected");
        // System.out.println("Not Connected");
        return false;
    }
    return false;
}

Now to check Internet Conncetion,

if (isInternetOn(this))
     {

        //Do stuff          
      }
else
       {

           //show alert
        }
Andro Selva
  • 53,910
  • 52
  • 193
  • 240