.isProviderEnabled(LocationManager.NETWORK_PROVIDE

2019-07-27 04:06发布

问题:

I don't know why, but my varaiable isNetowrkEnabled always return true. It doesn't matter if internet on my device is enabled or no.

This is my GPSTracker class:

public class GPSTracker extends Service implements LocationListener{

        private final Context mContext;

        boolean isNetworkEnabled = false;    
        boolean canGetLocation = false;

        Location location; // location

        protected LocationManager locationManager;

        public GPSTracker(Context context) {
            this.mContext = context;
            getLocation();
        }

    public Location getLocation() {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    System.out.println("Network enabled");
                } else {
                    System.out.println("Network disabled");
                }
            }   
    }

Do you know what may be wrong in this code?

回答1:

There is nothing wrong in your code, in all likelihood. Whether a provider is enabled is determined by the Location portion of the Settings app (or equivalent controls offered elsewhere by the device manufacturer, such as in an app widget). So long as the network provider is not disabled in Settings, isProviderEnabled(LocationManager.NETWORK_PROVIDER) will return true. The provider being enabled has nothing to do with whether the provider will work given your lack of network connection.



回答2:

Try this ..

ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
    return true;
}
else
{
    return false;
}


标签: android gps