How to run background jobs using threads
Previously I wrote about, that slow operations must be runned in threads. Now I would like to present some example code, how to use threads in Android.
Under the android system an user interface element can only be accessed from the thread that created it (the main UI thread). Thats where handlers and messages come in.
The user interface defines a handler like below:
- Handler handler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- int arg1=msg.arg1;
- int arg2=msg.arg2;
- MyClass myObject=(MyClass)msg.obj;
- //do something in the user interface to display data from message
- }
- }
Then the thread, which can not touch the user interface, sends a message to this handler instead.
The following example code, that implements file downloading from net, represents how I usually use the threads:
- public class Downloader {
- boolean interrupted=false;
- //see more at helloandroid.com/tutorials/how
-download-fileimage-url-your-d evice - ...
- while (((current = bis.read()) != -1) && !interrupted) {
- baf.append((byte) current);
- }
- ...
- if(interrupted){
- fileToSaveTo.delete();
- return null;
- }else
- return fileToSaveTo;
- }
- public void run() {
- Message message = new Message();
- try{
- message.obj=download(UrlToDownloadFrom,fileToSaveTo
); - message.arg1 = 0;
- message.arg1 = convertExceptionToErrorcode(e);
- }
- //notify the user interface that the download is ready
- handler.sendMessage(message);
- }
- }
- };
- thread.start();
- }
- public void interrupt(){
- interrupted=true;
- if(thread!=null && thread.isAlive())
- thread.interrupt();
- }
- }
This class offers functionality to run the downloading with and without a thread, th possibility to interrupt if started in a thread.
There is a built in class for this called AsyncTask but it is less flexible to use. For example you can not set the priority for AsyncTask jobs, and it bounds the background operation and the user interface operation together. But sometimes it is easier to use and a bit more efficient, maybe we will see AsyncTask in detail in a future article.
New tutorials from Helloandroid
Recent Apps
Android on Twitter
-
@Idevicegazette (iDevice Gazette)
GSM-to-Skype bridge lets you lose those roaming fees http://bit.ly/lbRJeh #android
11 years 37 weeks ago -
@tommy_banane (tom b.)
RT @AndroidFavorite: #Android New Desktop Android Market Is Live, Adds Several New Features http://zorr0.nl/lFwXNz
11 years 37 weeks ago -
@dwilliams5 (Dennis Williams)
just completed a runtastic run of 3.02 km in 40 min 11 s with #runtastic #Android App: http://tinyurl.com/5tvrpe3
11 years 37 weeks ago -
@S_Pinz (Spinz!)
RT @Androidheadline: Out of box #LG Optimus 3D got Quadrant 2420 score. Thanks @blink_c #io2011 #android http://twitpic.com/4whkdz
11 years 38 weeks ago -
@tayaitapps (Taya IT)
Next Google TV Looks A Lot Like Android http://t.co/dvlTim3 via @alleyinsider #google #apple #android #tv #honeycomb
11 years 38 weeks ago
Poll
Useful resources
Android Development Projects
- iOS/Android Developer to take older Games and bring them Current
- Android apps developer - need to finish urgent.
- Buliding MobileApp For onlie order
- looking for android APP developers
- Create an ecommerce app
- text-to voice for smartphones IOS - GOOGLE - HARMONY - AND ALEXA
- Optimize Images on App
- Create small feature with drag-drop text for Android
- Scouting for advanced website and Mobile apps developers. Potential Long-term contract.
- BLACK SCREEN