JnBrymn
JnBrymn

Reputation: 25353

Implementing simple service in Android

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

  1. Create a full on android.app.Service and bind my Activity to that Service? Or...
  2. 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.

Upvotes: 0

Views: 1477

Answers (4)

Rafael T
Rafael T

Reputation: 15679

I think an AsyncTask can do all the work for you. You have a doInBackgroud method, where you can query your API and send process messages if you want and update in onPostExecute. There you can start a new AsyncTask.

Upvotes: 0

Bear
Bear

Reputation: 1571

I answered this question about services in the past. You could tie in AsyncTask into the service to handle the web query

Upvotes: 0

treffer
treffer

Reputation: 784

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

Causes the thread which sent this message to sleep
for the given interval of time (given in milliseconds).
The precision is not guaranteed - the Thread may sleep
more or less than requested.

Both facts pretty much destroy the Thread-based idea. I'd highly recommend that you look into the android Service infrastructure.

Upvotes: 1

Cody Caughlan
Cody Caughlan

Reputation: 32748

Use the IntentService class / pattern. Create a onHandleIntent on your Activity which your android.app.Service instance will callback too and you're all set. Its lightweight and Android will take care of most of the housekeeping.

http://developer.android.com/reference/android/app/IntentService.html

Upvotes: 1

Related Questions