The code below does not work when the application is minimized or closed and doesn't return the current location.
For example, locationCallback only works once and does not work after the app is minimized. It should be noted that this service has been added to the manifest. It works in the video that I saw on YouTube YouTube Link
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);
}
}