Home How to create Long running background thread

postheadericon How to create and stop a long running background thread

To keep the user interface response during a long running process, two possible implementations are commonly used. You can either use a Service or a background thread. This article describes the usage of a background thread including what to do to stop the background thread. A sample application is provided to show the working.

The User Interface of an application must be responsive for the user at all times. To make that happen, possible long running processes must be executed within a separated thread. The sample application shows this principle. When the button 'Go' is pressed, a thread is created and started to do some long running processing. The actual work is coded within the LongRunningRunnable. In this sample, we just loop ten times and sleep 1 seconds between each loop. Finally, we send a message back to the foreground activity. We usethe Handler to send the message. And we have a ProgressDialog with a spinner to indicate that something is going on. The principle of a Handler and sending Messages is well described by Andriod. What not so well described is what to do in case the user wants to cancel the long running process. If you hit the back button, the ProgressDialog is dismissed. So far, so good. But, after a while the background thread still sends a message to the User Interface. To prevent this, we introduce a isRunning boolean as a member of the LongRunningRunnable. When we start the thread, isRunning is set to true. If the user cancels the request, the isRunning boolean must be set to false. To make that possible, we provide the ProgressDialog our own implementation of the OnCancelListener. The ProgressDialog is the one how recieves the cancel event. The implementation of the cancel method sets the isRunning boolean to false. The LongRunningRunnable looks at each loop if the isRunning boolean is still true. If not processing is stopped. Making use of a variable to stop processing is only visible if the long running process can be divided into several tasks. If you have one big chunk of work to be done, interrupting the thread is a better solution. Have fun and don't forget to like, plus or retweet if you like this blog.

The Long running process is used within the following apps:
- AdMob Statistics App

Attachments:
Download this file (SampleLongProcessing.zip)SampleLongProcessing.zip16 Kb