1
votes

Android doc says about runOnUiThread: "If the current thread is not the UI thread, the action is posted to the event queue of the UI thread."

My question is, will different activities share the same event queue or each activity has its own event queue?

Suppose activity A starts a thread to do something and finally updates UI using runOnUiThread, but at the same time it starts Activity B like the code below:

public class HelloAndroid extends Activity {
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       Thread myThread = new MyThread();
       myThread.start();

       Intent intent = new Intent(this, B.class);
       startActivity(intent);
   }

   private class MyThread extends Thread {

       public void run() {
           /* Do somthing expensive */
           ......

           /* Update UI */
           HellowAndroid.this.runOnUiThread(new Runnable() {
               @Override
               public void run() {

                   /* Do UI update for activity A */;
               }
           });

       }
   }
}

What if when the thread is executing the code "HellowAndroid.this.runOnUiThread(new Runnable...)", the visible activity is already B, and the stack is currently A B, with B at the top. Will the code "HellowAndroid.this.runOnUiThread(new Runnable...)" still be executed to update activity A? What will happen? Will activity A's UI be updated or not in this case?

Thanks.

1

1 Answers

3
votes

The Activity A thread code will still run and try to update the Activity A UI. But be warned, doing this you are at serious risk of running into runtime errors if the system has stopped your activity for any reason(such as running out of memory.)

It is much better practice to start threads on onResume and stop them again in onPause.