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
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() {
            @Override
            public void run() {
                for (int i = 0; i <= 10; i++) {
                    final int value = i;
                    doFakeWork();
                    progress.post(new Runnable() {
                        @Override
                        public void run() {
                            text.setText("Updating");
                            progress.setProgress(value);
                        }
                    });
                }
            }
        };
        new Thread(runnable).start();
    }

    // Simulating something timeconsuming
    private void doFakeWork() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }