java - android中后台服务中的当前位置不起作用
问题描述
当应用程序被最小化或关闭并且不返回当前位置时,下面的代码不起作用。
例如 locationCallback 只工作一次,应用最小化后就不能工作了。需要注意的是,该服务已添加到清单中。它适用于我在 YouTube YouTube 链接上看到的视频
public class UpdateLocationService extends Service {
static final int LOCATION_SERVICE_id = 175;
static final String ACTION_START_LOCATION_SERVICE = "startLocationService";
static final String ACTION_STOP_LOCATION_SERVICE = "stopLocationService";
private LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null && locationResult.getLastLocation() != null) {
double lat = locationResult.getLastLocation().getLatitude();
double lng = locationResult.getLastLocation().getLongitude();
Log.d(TAG, lat + ", " + lng);
}
super.onLocationResult(locationResult);
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void startLocationService() {
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(3000);
locationRequest.setFastestInterval(2000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.getFusedLocationProviderClient(this).requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
startForeground(LOCATION_SERVICE_id, builder.build());
}
private void stopLocationService() {
LocationServices.getFusedLocationProviderClient(this);
stopForeground(true);
stopSelf();
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
if (action != null)
if (action.equals(ACTION_START_LOCATION_SERVICE)){
startLocationService();
}else if (action.equals(ACTION_STOP_LOCATION_SERVICE)){
stopLocationService();
}
}
return super.onStartCommand(intent, flags, startId);
}
}
解决方案
Android O https://developer.android.com/about/versions/oreo/background后启动后台服务已被限制。如果你还想在后台获取什么位置,请考虑 WorkManger 和 Foreground services
推荐阅读
- python - Botometer 不断返回 TypeError
- c# - 如何在 webapi 项目中通过授权进行 http 调用?
- sql - SQL 查询:根据第 2 列中的值用第 1 列中的其他值填充空白/空值
- sql - 使用不包含视图的列对输出进行排序
- ios - CIFilter 卷积将 CIImage 维度倾斜到无穷大
- java - 有没有办法判断运行时类型是否被删除
- javascript - 如何解决 Javascript 扩展运算符表达式错误
- python - 如何逐步在变压器库上训练模型?
- javascript - 排序功能在 10 处停止并混淆 javascript
- xamarin.forms - 如何为跨平台对齐 xamarin 表单中的工具栏项