【问题标题】:Will handler.post(new Runnable()); create new Thread in Android?将 handler.post(new Runnable());在Android中创建新线程?
【发布时间】:2013-10-03 11:43:27
【问题描述】:

我编写了一个小应用程序,它每 3 秒更改一次应用程序背景。我使用 Handler 和 Runnable 对象来实现这一点。它工作正常。这是我的代码:

  public class MainActivity extends Activity {

        private RelativeLayout backgroundLayout;
        private int count;
        private Handler hand = new Handler();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Button clickMe = (Button) findViewById(R.id.btn);

            backgroundLayout = (RelativeLayout) findViewById(R.id.background);

            clickMe.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    count = 0;

                    hand.postDelayed(changeBGThread, 3000);

                }
            });

        }

private Runnable changeBGThread = new Runnable() {

        @Override
        public void run() {

            if(count == 3){
                count = 0;
            }

            switch (count) {
            case 0:
                backgroundLayout.setBackgroundColor(getResources().getColor(android.R.color.black));
                count++;
                break;

            case 1:
                backgroundLayout.setBackgroundColor(Color.RED);
                count++;
                break;

            case 2:
                backgroundLayout.setBackgroundColor(Color.BLUE);
                count++;
                break;

            default:
                break;
            }

             hand.postDelayed(changeBGThread, 3000);

        }
    };
}

这里我在非 UI 线程中更改 UI 背景,即 backgroundLayout.setBackgroundColor(Color.RED); inside run();它是如何工作的?

【问题讨论】:

    标签: android handler runnable ui-thread


    【解决方案1】:

    runnable 不是后台线程,它是可以在给定线程中运行的工作单元。

    Handler 不会创建新线程,它会绑定到它创建的线程的 looper(在本例中为主线程),或者绑定到您在构造过程中给它的 looper。

    因此,您没有在后台线程中运行任何东西,您只是在处理程序上排队一条消息,以便稍后在主线程上运行

    【讨论】:

    • 谢谢,正如我在这里看到的developer.android.com/reference/android/os/Looper.html 线程默认没有与之关联的消息循环,我们必须通过调用prepare() 来创建它。那么主线程是否默认有 Looper,因为我没有在我的应用程序中创建任何 Looper。
    • 是的,主 ui 线程有一个与之关联的 looper,您可以通过 Looper.getMainLooper() 获取它(如果您想检查处理程序绑定的 looper 也很有用)
    猜你喜欢
    • 1970-01-01
    • 2012-02-28
    • 2012-02-20
    • 2019-10-27
    • 2018-03-02
    • 2019-06-01
    • 2011-08-22
    • 2012-03-02
    • 1970-01-01
    相关资源
    最近更新 更多