将handler.post(new Runnable()); 在Android中创建新线程?

Pra*_*eep 4 android handler ui-thread runnable

我写了一个小应用程序,它每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);

        }
    };
}
Run Code Online (Sandbox Code Playgroud)

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

Fun*_*onk 14

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

处理程序不会创建新线程,它会绑定到它在(在这种情况下为主线程)中创建的线程的looper,或绑定到在构造期间给出的looper.

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

  • 是的,主要的ui线程有一个与之关联的looper,你可以使用Looper.getMainLooper()来获取它(如果你想检查一个looper处理器绑定的话,这很有用) (3认同)