在 Android 7.1 (API 25) 上,LocationManager 因 android.location.LocationListener.onStatusChanged

问题描述

当我在 Android 6.0 设备或 Android 10 上运行我的应用程序位置启用应用程序时一切正常,但当我在 Android 7.1 设备上运行它时,它在用户授予位置权限后立即崩溃并显示以下消息:

Process: com.hkc.incidencias,PID: 6853
java.lang.AbstractMethodError: abstract method "void android.location.LocationListener.onStatusChanged(java.lang.String,int,android.os.Bundle)"
    at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:304)
    at android.location.LocationManager$ListenerTransport.-wrap0(LocationManager.java)
    at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:242)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

My Fragment 实现了 LocationListener,它负责在请求位置更新之前检查用户权限。

private void startLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this.getContext(),Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this.getContext(),Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

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

    // Start updating the user location with a minimum update time and distance set so it doesn't affect too much the battery life.
    // Every time the position of the user changes,the onLocationChanged function will be called
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,20000,10,this);
}

然后它覆盖 onLocationChanged:

// The position of the user has changed
@Override
public void onLocationChanged(@NonNull Location location) {
    // Store the user position
    myPosition = new LatLng(location.getLatitude(),location.getLongitude());
   
    ...
}

解决方法

事实证明,在 build.gradle (:app) 中,如果我同时拥有 compileSdkVersiontargetSdkVersion 的值 30 代码编译得很好。但是如果我将这些值更改为 29 代码将不会编译说我需要实现 LocationListener

的以下方法
@Override
public void onStatusChanged(String provider,int status,Bundle extras){}

@Override
public void onProviderEnabled(String provider) {}

@Override
public void onProviderDisabled(String provider) {}

通过此更改,即使在返回 API 30 后,它也可在所有经过测试的设备上运行