How can I run code on a background thread on Android? How can I run code on a background thread on Android? multithreading multithreading

How can I run code on a background thread on Android?


IF you need to:

  1. execute code on a background Thread

  2. execute code that DOES NOT touch/update the UI

  3. execute (short) code which will take at most a few seconds to complete

THEN use the following clean and efficient pattern which uses AsyncTask:

AsyncTask.execute(new Runnable() {   @Override   public void run() {      //TODO your background code   }});


Remember Running Background, Running continuously are two different tasks.

For long-term background processes, Threads aren't optimal with Android. However, here's the code and do it at your own risk...

Remember Service or Thread will run in the background but our task needs to make trigger (call again and again) to get updates, i.e. once the task is completed we need to recall the function for next update.

Timer (periodic trigger), Alarm (Timebase trigger), Broadcast (Event base Trigger), recursion will awake our functions.

public static boolean isRecursionEnable = true;void runInBackground() {    if (!isRecursionEnable)        // Handle not to start multiple parallel threads        return;    // isRecursionEnable = false; when u want to stop    // on exception on thread make it true again      new Thread(new Runnable() {        @Override        public void run() {            // DO your work here            // get the data            if (activity_is_not_in_background) {                runOnUiThread(new Runnable() {                    @Override                    public void run() {                        // update UI                        runInBackground();                    }                });            } else {                runInBackground();            }        }    }).start();}

Using Service:If you launch a Service it will start, It will execute the task, and it will terminate itself. after the task execution. terminated might also be caused by exception, or user killed it manually from settings.START_STICKY (Sticky Service) is the option given by android that service will restart itself if service terminated.

Remember the question difference between multiprocessing and multithreading?Service is a background process (Just like activity without UI),The same way how you launch thread in the activity to avoid load on the main thread (Activity thread), the same way you need to launch threads(or async tasks) on service to avoid load on service.

In a single statement, if you want a run a background continues task, you need to launch a StickyService and run the thread in the service on event base


Simple 3-Liner

A simple way of doing this that I found as a comment by @awardak in Brandon Rude's answer:

new Thread( new Runnable() { @Override public void run() {   // Run whatever background code you want here.} } ).start();

I'm not sure if, or how, this is better than using AsyncTask.execute but it seems to work for us. Any comments as to the difference would be appreciated.

Thanks, @awardak!