4

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?

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Pradeep
  • 2,530
  • 26
  • 37

1 Answers1

15

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

FunkTheMonk
  • 10,908
  • 1
  • 31
  • 37
  • Thanks, As i read here http://developer.android.com/reference/android/os/Looper.html Threads by default do not have a message loop associated with them, We have to create it by calling prepare(). Then does Main Thread has Looper by default, bcoz i didn't create any looper in my application. – Pradeep Oct 03 '13 at 11:58
  • 3
    Yes, the main ui thread has a looper associated with it, and you can get it with Looper.getMainLooper() (which is useful if you want to check what looper a handler is bound too) – FunkTheMonk Oct 03 '13 at 13:11