Вопрос

I've created a custom Background Service, who is extending IntentService. I'm calling this class when my app goes to background via .startService(). Firsly onStartCommand is called where I'm returning START_STICKY (like I've read some other posts to keep my service alive and re-create if needed when is killed due to low memory). After that I'm implementing onHandleIntent(intent) method where I'm getting the extras from the caller intent and here I'm starting a Timer to run every minute and execute simple code. But the problem here is that, when the app is in background, after 30 mins my service is killed and not re-created. Here is part of my code, so any suggestions would be perfect.

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

@Override
protected void onHandleIntent(Intent workIntent) {
    //here I'm initializing the Timer
}

class UpdateTimeTask2 extends TimerTask {
     public void run() {
         backgroundTimer();//here I'm doing some simple coding
     }
}
Это было полезно?

Решение

So, as Kumar said, i should extend Service not IntentService. Calling of the service was the same as calling of the IntentService, the only difference was the unimplemented methods that were required by the Service class. Also I'm using Handler's postDelayed method instead of Timer and also in onStartComand I'm returning START_STICKY. So the service is not killed at all. Useful code can be found here and here. I hope this helps.

Другие советы

In this case a normal Service and a Handler should be all you need. As Pankaj wrote IntentServices are not designer for longrunning operations. You can then use the Handler's postDelayed method to excecute your code every minute.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top