确认已经获取了定位权限。
使用新的LocationCallback API替换旧的LocationListener API。
禁用应用程序的后台限制,以确保定位服务在应用程序后台运行时继续工作。
以下是使用新的LocationCallback API的示例代码:
LocationRequest locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(10000); locationRequest.setFastestInterval(5000); locationRequest.setNumUpdates(1);
FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { if (locationResult == null) { return; }
Location location = locationResult.getLastLocation();
// Do something with the location
}
}, Looper.getMainLooper());
请注意,该示例需要使用Google Play服务库。确保在应用程序的build.gradle文件中包含以下依赖项:
implementation 'com.google.android.gms:play-services-location:18.0.0'