Search code examples
androidandroid-locationandroid-gps

Listen for GPS Status change


I need to listen when the user turns GPS on or off, and act upon that.
I understand this was available using the GPSStatus class, however that was deprecated.
How do I do this now?


Solution

  • You can use LocationListener !!

    private class MyLocationListener implements LocationListener {
    
            @Override
            public void onLocationChanged(Location loc) {
                Toast.makeText(
                        getBaseContext(),
                        "Location changed: Lat: " + loc.getLatitude() + " Lng: "
                                + loc.getLongitude(), Toast.LENGTH_SHORT).show();
                //handlePostion(loc);
            }
            @Override
            public void onProviderDisabled(String provider) {
    }
    
            @Override
            public void onProviderEnabled(String provider) {}
    
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {}
        }
    

    And below how to use this listener

    mLocationListener = new MyLocationListener();
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            mLocationListener = new MyLocationListener();
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 5000, 10, mLocationListener);
    

    And in on providerDisabled callback you can know when the GPS is off