Handler (Associate Android Developer Certification)

Here you can find good post about UI and background interaction. I am writing this post as note for myself for future use. That’s why, in some points, it might be unclear.

If long running operation is happening in UI thread, show progress bar. Do not use blocking ProgressBar, user should be able to intereact with system.

Handler is created in new thread where it works. It opens channel to communicate with UI thread. Sent data can be instance of Message or Runnable. In order to send Message use method sendMessage(Message) or sendEmptyMessage(). In order to send Runnable use post() method.
You can reuse existing Activity’s handler to avoid to create new object:

handler = getWindow().getDecorView().getHandler();

Example code (from Vogella):

    public void startProgress(View view) {
        // do something long
        Runnable runnable = new Runnable() {
            public void run() {
                for (int i = 0; i <= 10; i++) {
                    final int value = i;
                    progress.post(new Runnable() {
                        public void run() {
        new Thread(runnable).start();

    // Simulating something timeconsuming
    private void doFakeWork() {
        try {
        } catch (InterruptedException e) {