要在最新的 Android 15 中获取位置,您应该使用 Fused Location Provider API,它是 Google Play 服务的一部分。此 API 提供了一种简单有效的方法来获取设备的位置,具有高精度和低功耗。 步骤:
-
添加依赖项:将必要的依赖项添加到您的
build.gradle
文件:
dependencies {
implementation 'com.google.android.gms:play-services-location:21.0.1'
}
-
请求权限:更新您的 AndroidManifest.xml 以包含必要的位置权限:
XML
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
-
在运行时检查权限:确保在运行时检查并请求位置权限:
Java
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_REQUEST_CODE);
return;
}
-
初始化FusedLocationProviderClient:在您的活动中创建FusedLocationProviderClient的实例:
Java
private FusedLocationProviderClient fusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
-
获取最后已知位置:使用 getLastLocation 方法获取最后已知位置:
Java
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations, this can be null.
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
// Use the location data
}
}
});