Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get android internet connection status? [duplicate]

Tags:

android

How to get android internet connection status for HTC One app development?

I'm new to android develpment and i'm going to develop an application with internet. so I need to get the interent status. Any help appreciated.

like image 331
MickeyTheNightHawk Avatar asked Feb 11 '14 09:02

MickeyTheNightHawk


2 Answers

Try this way and Read more

public static String getConnectivityStatusString(Context context) {
    int conn = NetworkUtil.getConnectivityStatus(context);
    String status = null;
    if (conn == NetworkUtil.TYPE_WIFI) {
        status = "Wifi enabled";
    } else if (conn == NetworkUtil.TYPE_MOBILE) {
        status = "Mobile data enabled";
    } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
        status = "Not connected to Internet";
    }
    return status;
}

Or another simple way to achieve the task

private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
    if (ni.getTypeName().equalsIgnoreCase("WIFI"))
        if (ni.isConnected())
            haveConnectedWifi = true;
    if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
        if (ni.isConnected())
            haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}

And in your android manifest:

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

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

`<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />`
like image 170
3 revs, 2 users 89% Avatar answered Nov 14 '22 23:11

3 revs, 2 users 89%


Use this code : This code will work in all android version..

public static boolean isInternetOn(Context context) 
    {
         boolean haveConnectedWifi = false;
         boolean haveConnectedMobile = false;

         ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo[] netInfo = cm.getAllNetworkInfo();
         for (NetworkInfo ni : netInfo) 
         {
             if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                 if (ni.isConnected())
                     haveConnectedWifi = true;
             if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                 if (ni.isConnected())
                     haveConnectedMobile = true;
         }
         return haveConnectedWifi || haveConnectedMobile;
    }

It returns the true if internet is on and false when internet is not available.

like image 25
Mehul Ranpara Avatar answered Nov 15 '22 00:11

Mehul Ranpara