Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will handler.post(new Runnable()); create new Thread in Android?

I wrote a small app which changes application background every 3 sec. I used Handler and Runnable object to achieve this. It's working fine. Here is my code:

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

        }
    };
}

Here I'm changing UI background in non-UI thread, i.e backgroundLayout.setBackgroundColor(Color.RED); inside run(); how it is working?

like image 589
Pradeep Avatar asked Dec 06 '22 05:12

Pradeep


1 Answers

A runnable isn't a background thread, it is a unit of work that can be run in a given thread.

Handler doesn't create a new thread, it binds to the looper of the thread that is it created in (the main thread in this case), or to a looper you give it during construction.

Therefore, you're not running anything in a background thread, you are just queuing a message on the handler to run at a later point in time, on the main thread

like image 69
FunkTheMonk Avatar answered Dec 28 '22 06:12

FunkTheMonk