JavaForAndroid
JavaForAndroid

Reputation: 1179

Check network connection with LocationManager in Android

I would like to check the network connection with the LocationManager in Android. My code works fine with Galaxy SII and Version 4.0.3. But it does not work with Galaxy S and Version 2.3.6.

The code:

 isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
 isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

I am connected to a Wi-Fi network for sure. But the if statement

if (!isGPSEnabled && !isNetworkEnabled)

returns true. Are there known bugs and is there a reliable way to check it?

Upvotes: 0

Views: 857

Answers (3)

Gru
Gru

Reputation: 2694

Try this out:

    //If you only want to check your Internet connection available or not    
        public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
                        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                        return activeNetworkInfo != null && activeNetworkInfo.isConnected();}

Note: wifiInfo provide you status about your Wifi, still it will be there poor connection I think it will good if make HTTP reuest, for more details check link provided.

Edit: For more information you can [refer this][1].

Upvotes: 1

Shivang Trivedi
Shivang Trivedi

Reputation: 2182

Use this code:

 public static boolean checkConn(Context ctx)
{

    ConnectivityManager conMgr =  (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo wifiInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    NetworkInfo mobileInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);    
    NetworkInfo info = conMgr.getActiveNetworkInfo();

    if(info != null && info.isConnected()) {  
        Log.v("NetworkInfo","Connected State");  
        return true;
    }  
    return false;
}

Upvotes: 0

Ripal Tamboli
Ripal Tamboli

Reputation: 572

I am using below code in my every android project. It will check for any active network that are used for outgoing connection.

public static boolean isNetworkAvailable(Context context)
    {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnectedOrConnecting())
            return true;

        return false;
    }

Upvotes: 0

Related Questions