Is it possible to get a notification when any location provider is enabled/disabled and ascertain what action occurred?

前端 未结 4 2322
挽巷
挽巷 2021-02-20 18:32

I wish to receive a notification when the user enables or disables either Network or GPS locations, and importantly I wish to know which one they have changed and how. I have a

4条回答
  •  误落风尘
    2021-02-20 19:35

    I hope that this doesn't contradict your requirement

    I know that I could keep the state of each provider and then when I receive notification that they have changed then I could work out what has changed, I am looking for a more "standard" method of doing this.

    ...but I would think the best, "standard", and most flexible way of doing this is to let your LocationProviderChangedReceiver implement the LocationListener interface and then implement onProviderEnabled() and onProviderDisabled() like so:

    public void onProviderEnabled(String provider) {
      if(provider.equals(LocationManager.GPS_PROVIDER)){
        ...
      } else if (provider.equals(LocationManager.NETWORK_PROVIDER)){
        ...
      }
    }
    

    Note that you should add the ACCESS_FINE_LOCATION permission to your manifest if you haven't already. Also, other providers (beyond "Network" and "GPS") may apply depending on the context, like PASSIVE_PROVIDER or even FUSED_PROVIDER.

    Updated answer:
    If constantly listening for location changes is no option for you, the LocationManager also knows which provider is currently enabled:

    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    

    ...so that you could use these checks together with your BroadcastReceiver to avoid manually holding any enabled/disabled flags. Beyond that, there is an intent called android.location.GPS_ENABLED_CHANGE which you could try to receive (and process) as well. But since this intent is hidden in the official documentation, it might not be safe to use it, as mentioned in this answer.

    Even another approach:
    Android's default settings toggle widget (you know what I mean) displays the GPS enabled/disabled state by subscribing to the android.location.PROVIDERS_CHANGED intent (like you do) to trigger a request of the GPS state via the user settings:

    @Override
    public int getActualState(Context context) {
      ContentResolver resolver = context.getContentResolver();
      boolean on = Settings.Secure.isLocationProviderEnabled(
                     resolver, LocationManager.GPS_PROVIDER);
      return on ? STATE_ENABLED : STATE_DISABLED;
    }
    

    (from the official sources).
    You could adapt this approach for other location providers as well.

提交回复
热议问题