Reputation: 81
I have to perform a repeated tasks (download data from internet) in a Service. I did the task with the following code:
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mHandler.post(mTask);
return START_STICKY;
}
private final Runnable mTask = new Runnable() {
@Override
public void run() {
downloadData(url);
mHandler.postDelayed(this, mDelay);
}
};
@Override
public void onDestroy() {
mHandler.removeCallbacks(mTask);
}
}
If I want to use an IntentService instead a service and move mHandler.post(mTask);
to onHandleIntent the code is executed only 1 time because then the IntentService is killed.
@Override
public void onHandleIntent(Intent intent) {
mHandler.post(mTask);
}
Can I prevent this and make the IntentService running?
Upvotes: 0
Views: 1372
Reputation: 1007369
If the service overall will not be around very long, and if mDelay
is short (a minute or less), you may just want to stick with your original implementation.
If mDelay
is long, you should use AlarmManager
, so your service is only in memory while it is doing work. In that case, the AlarmManager
alarm is handing the periodic repeat.
Upvotes: 2