3

i developing the project that is uses the internet my problem is that check the application is connected to internet or not i used the fallowing code but error is generated

public void onClick(View v)
{
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info= cm.getActiveNetworkInfo();
    boolean a= cm.getActiveNetworkInfo().isConnectedOrConnecting();
    if(a==true){
        Toast("Connected");
    }
    else{
        Toast("Not Connected");
    }
}
Vikas Patidar
  • 42,865
  • 22
  • 93
  • 106

3 Answers3

11

Please try below function . If internet connection is available in device then it will return true otherwise it will return false.

public static boolean CheckInternet(Context context) 
{
    ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (wifi.isConnected()) {
        return true;
    } else if (mobile.isConnected()) {
        return true;
    }
    return false;
}

Add Permission in android manifest file.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Chirag
  • 56,621
  • 29
  • 151
  • 198
0

Add this in AndroidManifest file , if you haven't done it yet.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

check here,
How can I monitor the network connection status in Android?

Community
  • 1
  • 1
sat
  • 40,138
  • 28
  • 93
  • 102
0
try {
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 
NetworkInfo info= conMgr.getActiveNetworkInfo(); 

    if(info != null && info.isConnected()) 
    {
        //Internet is there
    }
    else{
        //Internet is not there
    }
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

hope it will help you...

wallyk
  • 56,922
  • 16
  • 83
  • 148
Sumant
  • 2,775
  • 2
  • 22
  • 30