Reputation: 25
I need to implement a background task that needs to update the UI about every 10 seconds. I tried the following approaches, but most of them failed.
1) AlarmManager
I started an intent service via AlarmManager. It seems that AlarmManager is only suitable for very low frequencies, like several hours. If I set it to 10 seconds, then the UI does not respond anymore. Why is that? Doesn't the intent service run in a separate thread?
2) IntentService with infinite loop and Thread.sleep
App was terminated after about 30 seconds, UI was not responding at all. Is intent service only for very short background tasks? I found contradicting information about this. Why is the UI not responding although intent service should run in a separate thread?
3) AsyncTask
When using AsyncTask, the UI remains responsive. But for some reasons, no other AsyncTask is started from the UI. I heard about some limits of concurrend AsyncTasks, but 2 should not be too much?
4) Own Threads
That worked. Background service and UI are fully functional. However, I read that it is bad practise to use threads directly when updating the UI. What would be the best way in this context to send data to the Activity?
What do you recommend for a background task that needs to update the UI and reoccures about every 10 seconds?
Best regards!
Upvotes: 2
Views: 506
Reputation: 4831
Since you need the task to happen in recurring fashion, i would think Alarm Manager is better option.
These are my reasons.
As per android documentation,
For timing operations that are guaranteed to occur during the lifetime of your application, instead consider using the Handler class in conjunction with Timer and Thread. This approach gives Android better control over system resources.
Upvotes: 1