Android Loopers and Handlers – Code Tutorial

In our last post we tried to understood the concept of Looper and Handler. Now let us implement these in this tutorial. We will be creating a download manager which download files(we are using delay for this simulation) one by one.

Implementation Details

Basically, I created a DownloadTask class that emulates a download task of a random duration. I did not want to do actual downloads because I didn’t want to eat your data plans, but it’s straightforward to change this into real work. Then, the DownloadThread has an interface that allows to enqueue DownloadTask instances and also to request it to exit gracefully. There is also the DownloadThreadListener interface that allows the download thread to notify some other entity about status updates. In our case, that interface will be implemented by the  DownloadQueueActivity because we want to reflect the download progress in the UI.

Source code:

 

 

Preview:

Lets get started :

1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details.

2. Lets create DownloadThreadListener.java interface which will be used to get thread updates.

3. Lets now create a class named DownloadTask.java which will simulate the downloading. We will be using random time sleep to simulate the download time.

 4. Now lets create the thread subclass which will act as pipeline. First we will call Looper.prepare() to make this Thread act as pipeline. Next new Handler() will be called to handle message queue on this thread. Finally Looper.loop() will be called to start running the message loop. New tasks will be added using enqueueDownload(final DownloadTask task) . Code for DownloadThread.java

5. Now add full functionality to MainActivity.java . Here also we will create handler so that we can post events on main thread.

6. Lets add this code to activity_main.xml

7. Lets also update AndroidManifest.xml . Add vibrate permission.

8. Now build and run the project.

guru

Technology enthusiast. Loves to tinker with things. Always trying to create something wonderful using technology. Loves coding for Android, Raspberry pi, Arduino , Opencv and much more.

You may also like...