Application is closed after a while, even with service

0

Hello, I have a service that runs in the background, this service should not be terminated by the Android system, but this happens after a run time.

public class VerificaCorridas extends Service {

private Timer timerAskServer;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    verifyServer();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
    super.onDestroy();
    timerAskServer.cancel();
}

@Override
public void onCreate() {
    super.onCreate();
}


@Override
public IBinder onBind(Intent intent) {
    return null;
}

public void verifyServer() {
    timerAskServer = new Timer();
    TimerTask askServer = new TimerTask() {
        public void run() {
            // Aqui é feito uma consulta ao servidor para ver se tem algo novo
        };

    };
    timerAskServer.schedule(askServer, 0, 10000); //repete a cada 10 Seg
}

}

    
asked by anonymous 27.07.2015 / 20:21

2 answers

0

Generally speaking, any Android service can be stopped at any time, particularly if the phone has low memory. This is how the platform works.

An alternative to ensure that it comes back after an outage is to restart it periodically with an Alarm.

Another rather intrusive alternative is to start the service with startForeground . In this mode a notification is permanently in the notification area (it can not be "dismissed" by the user) which "holds" the service in memory.

Services that spend resources and run all the time should use this solution, according to the Android UI Guidelines. For example: a music application, which is using audio all the time and should not be interrupted.

That said, a service with permanent notification STILL can be stopped in case of absolute lack of memory. So Alarm is still needed if you want to make sure it runs 24x7.

    
27.07.2015 / 20:48
0

As an Android developer it is important to keep in mind that you have no control over the life cycle of an application. At any time, your device may run out of resources (for example, memory is out) and the system will terminate the application to keep the OS running properly.

This behavior is valid for any part of your application. That way, you need to use a AlarmManager ( link ) to periodically trigger your service and do the verification. It's not cool to keep a service running forever, so as not to be intrusive and consume unnecessary user resources.

    
27.07.2015 / 23:45