Вопрос

I'm planning to have a button in an activity which will start a service when clicked. However, GPS needs to be enabled for the service to do its work so I'd like to have the button disabled if GPS is disabled. Is there a way to get android to notify my activity when GPS is enabled/disabled so that I can enable/disable the button accordingly?

Это было полезно?

Решение

This link describes how to create a location listener: http://blog.doityourselfandroid.com/2010/12/25/understanding-locationlistener-android/

I've copied the important parts down below in case the site goes down in the future. The first step is to create a LocationListener:

private final class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location locFromGps) {
        // called when the listener is notified with a location update from the GPS
    }

    @Override
    public void onProviderDisabled(String provider) {
       // called when the GPS provider is turned off (user turning off the GPS on the phone)
       // Dim the button here!
    }

    @Override
    public void onProviderEnabled(String provider) {
       // called when the GPS provider is turned on (user turning on the GPS on the phone)
       // Brighten the button here!
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
       // called when the status of the GPS provider changes
    }
}

Then you'll want to register that listener. This should probably go in your onCreate()

LocationListener locationListener = new MyLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 35000, 10, this.locationListener);

The second and third parameters in requestlocationupdates you should probably make huge so you don't get locationupdates since you don't really care about those, only provider enabled/disabled changes.

Другие советы

Please use this code to get the GPS status. use this code in the onResume of the activity

private LocationManager mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean GPSprovider = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

and according to the GPSProvider you can enable and disable the button.

try this

final String GpsProvider = Settings.Secure.getString(
                getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (GpsProvider.equals(""){
//No GPS
}else{
 //GPS available 
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top