简体   繁体   中英

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?

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

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;
    }

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM