关于runOnUiThread问题 [英] Question about runOnUiThread

查看:243
本文介绍了关于runOnUiThread问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android的医生说大约runOnUiThread:如果当前线程不是UI线程,该动作被发布到UI线程的事件队列。

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?

假设活性的启动一个线程做一些事情,最后更新使用runOnUiThread用户界面,但同时它像下面的code开头活动B:

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 */;
               }
           });

       }
   }
}

如果当线程执行codeHellowAndroid.this.runOnUiThread(新的Runnable ...),可见活动已经是B,且堆栈目前A B,为B顶部。将在codeHellowAndroid.this.runOnUiThread(新的Runnable ...)仍然可以执行更新活动的阿?会发生什么?将活动A的UI在这种情况下被更新或不?

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?

感谢。

推荐答案

活性的线程code将继续运行,并尝试更新活动的UI。但要注意,在运行到运行时错误的严重危险这样做,你的系统是否停止您的活动因某种原因(如内存溢出。)

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.)

有更好的做法是在onResume启动线程,并在再次的onPause阻止他们。

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

这篇关于关于runOnUiThread问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆