Let’s say that I want to create a service (note: lowercase – I’m not implying a android.app.Service) on an Android device that queries a web API every 30 seconds and provides any updates to the subscribed Activity. I only anticipate one Activity will ever be subscribed to this service. Should I
- Create a full on android.app.Service and bind my Activity to that Service? Or…
- Create a lightweight “service” (lowercase) which is basically a thread that implements the observer pattern and periodically updates any registered observers (of which there should only ever be one) with new information.
URLs to online examples would also be appreciated.
Never expect your Activities to stay alive
Your Activity should not start a Thread except for short-period offloading of work. The system may always suspend the Activity. You may thus not rely on an activity to keep running.
This pretty much means that a Thread is a no-go. Also note that Thread.sleep has no accuracy. It may misfire and wakeup too early or too late. See the android:java.lang.Thread.sleep documentation
Both facts pretty much destroy the Thread-based idea. I’d highly recommend that you look into the android Service infrastructure.