Sartheris Stormhammer
Sartheris Stormhammer

Reputation: 2564

Foreground service being stopped by Android does not restart later

I have a Foreground Service for my app, which must run the whole time and never stops. While I was testing it few times, it seems after 3-4 days Android decides it just to stop it, and never restart it again, and in my Activity I have a check for the service if its running, and if it isnt to start it. Even though, the service is not starting, and I can't debug it, because this is not happening immidiatelly. So this is my check, is there something wrong in it?

if (!isMyServiceRunning(MyService.class)) {
        startService(new Intent(this, MyService.class));
}

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

I call this check in onResume() of the Activity, and I can't just run it everytime when the activity starts, because I have a constantly running Thread in the service, which will get more than one instance if started several times...

So here is what I want: Either have more reliable way to check for the service if its running or Just start the service every time the activity starts, to prevent problems, and the thread inside of it must always have just 1 instance (I have already declared is as static)

Upvotes: 2

Views: 869

Answers (1)

Kiril Aleksandrov
Kiril Aleksandrov

Reputation: 2591

You can make your service Bindable and bind your Activity to the service when the Activity starts/resumes. This way you will be sure the service is running. But I think you have a problem with your service. My I ask you to post more information about the service? It is not normal the OS to kill a foreground service with no traces.

Upvotes: 1

Related Questions