在Android 12中,使用LocationManager的getLastKnownLocation方法会产生一个意外行为。当应用程序新安装时,如果getLastKnownLocation方法调用得太早,则可能会返回null值。这是因为在Android 12中,Google已经更改了Google Play服务的默认设置,因此LocationManager和Google Play服务成为了单独的实体。
为了解决此问题,可以在LocationManager请求位置更新之后再调用getLastKnownLocation方法。以下是使用requestLocationUpdates方法获取位置后再调用getLastKnownLocation的代码示例:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// 获取位置后调用getLastKnownLocation方法
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation != null) {
// 确定用户位置
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
// 请求位置更新
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);