Android Handler Examples

A Handler in Android is a construct that can be used to communicate between UI thread and separate background threads. A handler belongs to the thread that is creating it. For example, if you create a handler in the onCreate method of an Activity, it belongs to the UI thread, and this is usually what you want to do because you can then use this handler to post feedback to the UI thread from background threads.

The following are 3 examples of using handler in an Activity class in Android. First of all, here are some boilerplate code for housing the real handler examples.

TextView tvDisplay;
Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    tvDisplay = (TextView) findViewById(R.id.tv_display);
    mHandler = new Handler(); // The handler is created here in the UI thread

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            takeNap();            
            doFakeWork();
            checkInternetConnection();
            
        }
    });
}

1st handler example, taking a nap. This example uses the sendMessage and handleMessage Mechanism.

private void takeNap() {
    final Handler handler = new Handler() {
      @Override
      public void handleMessage(Message msg) {
          super.handleMessage(msg);
          tvDisplay.setText(msg.obj + "\n" + tvDisplay.getText());
      }
    };
    new Thread(new Runnable() {
        @Override
        public void run() {
            // sleep for 5 seconds
            try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}
            Message msg = new Message();
            msg.obj = "I've taken a nap!";
            handler.sendMessage(msg);
        }
    }).start();
}

2nd handler example, the mHandler was declared as a member variable in the activity class thus it is bond to the UI thread, this example calls post on this handler in the background thread to update the TextView.

private void doFakeWork() {
    new Thread(new Runnable() {
        @Override
        public void run () {
            // do some fake work
            try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}

            // post result back to the UI thread
            mHandler.post(new Runnable() {
                @Override
                public void run () {
                    tvDisplay.setText("doFakeWork completed\n" + tvDisplay.getText());
                }
            });
        }
    }).start();
}

3rd handler example, similar to the 2nd example, but this time instead of doing some fake work, it is actually performing some real work which is to check if there is internet connection. This check process is ran in a background thread.

private void checkInternetConnection() {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            final boolean hasConnection = isConnectedToServer("http://www.google.com", 1000);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    tvDisplay.setText("hasConnection: " + hasConnection + "\n" + tvDisplay.getText());
                }
            });
        }
    });
    t.start();
}

private boolean isConnectedToServer(String url, int timeout) {
    try {
        URL myUrl = new URL(url);
        URLConnection connection = myUrl.openConnection();
        connection.setConnectTimeout(timeout);
        connection.connect();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        // Handle your exceptions
        return false;
    }
}

Lastly, if the handler is declared as a member variable of an Activity or Fragment class, remember to clean up the handler in the onPause or onDestroy method by calling mHanlder.removeCallbacksAndMessages(null);

Search within Codexpedia

Custom Search

Search the entire web

Custom Search