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

前端 未结 4 2288
挽巷
挽巷 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:23

    Thanks to @usman 's answer we can apply the solution without extends the class by the following way;

    AndroidManifest.xml;

    
        
            
        
    
    

    class (I never tested);

    public class LocationProviderChangedReceiver {
    
        private mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        private BroadcastReceiver mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String ability = (isGPSProviderEnabled() && isNetworkProviderEnabled()) ? "CAN" : "CANNOT";
                Log.d("", "The location " + ability + " be caught in high accuracy!");
            }
        };
    
    
        public startProviderChangeObserving () {
            registerReceiver(mReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
    
        }
    
    
        public stopProviderChangeObserving () {
            unregisterReceiver(mReceiver);
        }   
    
    
        /**
        * Method to verify that the location providers wheter on or not on the device
        **/
        public boolean isGPSProviderEnabled() {
            return (Boolean) mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        }
    
        public boolean isNetworkProviderEnabled() {
            return (Boolean) mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        }
    
    }
    

提交回复
热议问题