0

The service runs in the background all the time, but for some reason my function saveUserLocation();, stop after some time. When the app is open it runs the whole time. Here is some pictures to show the service still runs in the background after I close the app, and the other picture I close the app and then the logD still prints for some seconds, then it stops.

service in background

service

LogD -> logcat suddenly just stops

logcat

Code from service

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand: called");

    notificationGenerator();
    getLocation();
    return START_NOT_STICKY;
}

private void getLocation() {
    // ---------------------------------- LocationRequest ------------------------------------
    // Create the location request to start receiving updates
    LocationRequest mLocationRequestHighAccuracy = new LocationRequest();
    mLocationRequestHighAccuracy.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequestHighAccuracy.setInterval(UPDATE_INTERVAL);
    mLocationRequestHighAccuracy.setFastestInterval(FASTEST_INTERVAL);
    mFusedLocationClient.requestLocationUpdates(mLocationRequestHighAccuracy, new LocationCallback() {
                @Override
                public void onLocationResult(LocationResult locationResult) {
                    Log.d(TAG, "(*) Service Running");
                }
            },
            Looper.myLooper()); // Looper.myLooper tells this to repeat forever until thread is destroyed
}

Manifest

<service android:name=".service.Service"
android:enabled="true"
android:exported="true"/>

It dosen't say any error in Logcat, it just stops, and when I start the app again it continues. Any ideas why it stops?

Mads
  • 61
  • 1
  • 8

1 Answers1

0

When app is closed the service gets also closed. Because they are in one thread, so that service should be run on another thread so it cannot be closed, So there is two way to alive the service.

1:Use alarm amanger (Follow this [https://stackoverflow.com/a/34790376/8918150][1])

2:You can also use startForeground(). And this is a good approach to do that

Usama khan
  • 81
  • 6
  • I do use StartForeground();' – Mads May 04 '20 at 21:22
  • Yes as i said this is the best approach. Is consume less batery. But if you think it is necessary to always alive the service use the first option. And this is also the way . to receate your service by broadcast reciever. Have a look at it. https://stackoverflow.com/a/52258125/8918150 – Usama khan May 04 '20 at 22:04