Skip to content

Instantly share code, notes, and snippets.

@OrenBochman
Last active September 10, 2018 20:20
Show Gist options
  • Save OrenBochman/ce59c659fbfabde715ca0871d62f17bc to your computer and use it in GitHub Desktop.
Save OrenBochman/ce59c659fbfabde715ca0871d62f17bc to your computer and use it in GitHub Desktop.
HandlerThread in Android

HandlerThread in Android

The HandlerThread is a convenience class that initiates a Looper within a Thread to process Runnable or Message objects. The Handler is used to handle the insertion of the Runnable or Message objects into the looper's queue: The Handler class supports several other ways to schedule a Message to be processed at a future time:

Queueing tasks

  • sendMessage - Pushes a message onto the end of the message queue.
  • sendMessageDelayed - Pushes a message onto the end of the message queue.
  • sendMessageAtTime - Pushes a message onto the end of the message queue.
  • sendEmptyMessage - Sends Message containing only a single int code.
  • sendEmptyMessageDelayed - Sends Message to be delivered after the specified time elapses.
  • sendEmptyMessageAtTime - Sends Message to be delivered at the specified absolute time.

Stopping

handlerThread.quit(); // quits immediately

// Create a new background thread for processing messages or runnables sequentially
HandlerThread handlerThread = new HandlerThread("HandlerThreadName");
// Starts the background thread
handlerThread.start();
// Create a handler attached to the HandlerThread's Looper
mHandler = new Handler(handlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
// Process received messages here!
}
};
// Execute the specified code on the worker thread
mHandler.post(new Runnable() {
@Override
public void run() {
// Do something here!
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment