Skip to content
Joshua Rogers edited this page Dec 27, 2013 · 3 revisions

See Android threads page for more detail.

Threads can be run as regular java threads on android. For example,

public void onClick(View v) {
    new Thread(new Runnable() {
        public void run() {
            //do something on this thread
        }
    }).start();
}

All UI on Android runs on one thread. The main rules are:

  1. Do not block the UI thread
  2. Do not access the Android UI toolkit from outside the UI thread

There are two ways to modify the UI from another thread, you can post a Runnable to the UI thread or use AsyncTask

Example of posting to ui thread (from an Activity, in onCreate or something like that):

new Thread(new Runnable(){
    //do something in another thread
    runOnUiThread(new Runnable(){
        //do some UI manipulation
    })
}).start();

Example of AsyncTask:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

Clone this wiki locally