Learn by doing Android — Services and Intent Services(3/3)

Shivam Dhuria
2 min readJun 3, 2019

--

This is the final part of a 3 part series.

Part 1 — Foreground Services

Part 2 — Bound Services

Intent Services

Intent Service is a subclass of Service.Anything that a Intent Service does can also be done using our good old Service class.

What’s the point of Intent Service then?

The primary features of intent service are

  • It automatically queues up intents if an intent is already being processed at onHandleIntent() .
  • It runs on a single worker thread while service runs on the main thread(from where it’s called),only one request will be processed at a time.
  • It stops itself after all the requests are handled, while for services, stopSelf() or stopService() have to be called.
  • It can only be invoked from main thread.

For someone who doesn’t want to reinvent the wheel , IntentService is the way to go.

Learn by Doing

We’ll create an application that send a text message with intent and returns the same message after processing it in the worker thread for 5 seconds.We will create a broadcast receiver in the Main Activity to update the textview.

Keep an eye on the Toast, that’s where the magic happens!

activity_main.xml

MyService.java

The intent is passed to OnHandleIntent(), after completing the task we use LocalBroadcastManager to send a broadcast to update the UI.

MainActivity.java

Make sure to set up receiver on onStart() and unregister on onStop().

When the button is clicked, the service is started and the worker thread begins to run. Shorty the intent service is destroyed if there are no pending intents.

However if a message is submitted more than once before the service is destroyed, the intent gets added to a queue and the service in only destroyed when all the pending intents are finished.

AndroidMainfest.xml

You can find the repository on Github.

References

--

--

No responses yet