在Android 12中,更改了对后台位置权限的访问。如果要在后台访问设备位置,则需要在Android 12及更高版本中使用新的接口。
以下是访问位置的示例代码,其中包含必要的权限请求和后台位置服务的启动:
首先,要在AndroidManifest.xml文件中添加位置权限:
然后,在Activity或Service中,使用如下代码请求位置访问权限:
private static final int REQUEST_LOCATION_PERMISSION = 1;
private void requestPermission(){
if (ContextCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_LOCATION_PERMISSION
)
}
}
接下来,在Service中使用如下代码请求位置更新:
private static final long MIN_TIME = 1000; // 每秒更新一次位置
private static final float MIN_DISTANCE = 10; // 当位置改变10米时更新位置
private FusedLocationProviderClient fusedLocationClient;
private void startLocationUpdates() {
LocationRequest locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(MIN_TIME)
.setFastestInterval(MIN_TIME)
.setSmallestDisplacement(MIN_DISTANCE);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationClient.requestLocationUpdates(locationRequest, callback, Looper.getMainLooper());
}
private final LocationCallback callback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null) {
Location location = locationResult.getLastLocation();
// 处理位置信息
}
}
};
请注意,上面的代码是在Service中使用FusedLocationProviderClient请求位置更新的示例。如果需要在其他组件中访问位置,请相应地更改代码。
如果您需要在Android 12及更高版本中后台访问位置,请确保遵循上述示例中的步骤并在AndroidManifest.xml文件中添加必要的权限。