首页 > 解决方案 > 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);

}

}

标签: javaandroidgpslocationbackground-service

解决方案


Android O https://developer.android.com/about/versions/oreo/background后启动后台服务已被限制。如果你还想在后台获取什么位置,请考虑 WorkManger 和 Foreground services


推荐阅读