Can a service be killed by the android?

1

I know that depending on how long an Activity is onPause () and if the device needs to free memory it will kill that Activity / em>. I wonder if the same thing happens with the service that runs in the background? When Activity is killed, the service will also be killed?

I have a service that does a location update using the Google Maps API from time to time, however I believe that after a long time, and the user is using other applications, he is dead.

    
asked by anonymous 06.04.2016 / 14:05

1 answer

1

Contrary to what documentation seems to suggest, to free memory the system does not kill Activity but rather the entire process of your application. Usually the services are killed together, because they belong to the same process (although it is possible to define them to run in separate, though uncommon processes).

You can reduce the odds of the service being killed, putting it to run in "foreground" (foreground). But it is not very desirable as it makes the user aware of the service running through a notification in the notification bar.

The ideal depending on the situation would be to define that the service should be restarted even in case the process dies. This is done through flags such as START_STICKY :

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //**Seu código**
    return START_STICKY;
}
    
06.04.2016 / 14:56