androidlocationmanager

Android LocationListener, AbstractMethodError on onStatusChanged and onProviderDisabled


I have a simple activity with a button, that uses the LocationManager to try to get the current location:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button buttonGps = findViewById(R.id.buttonGps);

    final Context activity = this;

    buttonGps.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!checkForPhonePermission()) {
                return;
            }

            LocationManager locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

            locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, new LocationListener() {
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    Log.d(TAG, location.getLatitude() + "");
                }
            }, Looper.myLooper());
        }
    });
}

I created an emulator in Android Studio with the API level 22, and after giving the permission, and with the gps of emulator on, the app crashes with this error when clicking the button:

java.lang.AbstractMethodError: abstract method "void android.location.LocationListener.onStatusChanged(java.lang.String, int, android.os.Bundle)"

If I press the button with the gps turned off, I get this error instead:

java.lang.AbstractMethodError: abstract method "void android.location.LocationListener.onProviderDisabled(java.lang.String)"

If I try the app on my Xiaomi Mi A1, it only crashes when the gps is off and the button is clicked, it does not crash when the gps is on and the button is pressed.

From the documentation, those methods are marked with default, so I should not need to implement them.

Is there any reason for this behavior?


Solution

  • Just add these three function at the end of your code:

    @Override
    public void onProviderEnabled(@NonNull String provider) {
    
    }
    
    @Override
    public void onProviderDisabled(@NonNull String provider) {
    
    }
    
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        
    }
    

    and write your code that you would like to execute when status changes