Skip to content

Instantly share code, notes, and snippets.

@OrenBochman
Last active September 10, 2018 16:43
Show Gist options
  • Save OrenBochman/8f1a15a43c98c3e413198e76855809bb to your computer and use it in GitHub Desktop.
Save OrenBochman/8f1a15a43c98c3e413198e76855809bb to your computer and use it in GitHub Desktop.
Handler - schedule periodic tasks in Android

Handler - Stub

Use a Handler to run code on a given thread after a delay or repeat tasks periodically on a thread.

  1. constructing a Handler and then
  2. "posting" Runnable code to the event message queue on the thread to be processed

Handler can communicate with UI-thread

handler.post(); handler.postAtFrontOfQueue(); handler.postDelayed(); handler.postAtTime();

// We need to use this Handler package
import android.os.Handler;
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
@Override
public void run() {
// Do something here on the main thread
Log.d("Handlers", "Called on main thread");
}
};
// Run the above code block on the main thread after 2 seconds
handler.postDelayed(runnableCode, 2000);
// We need to use this Handler package
import android.os.Handler;
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
@Override
public void run() {
// Do something here on the main thread
Log.d("Handlers", "Called on main thread");
// Repeat this the same runnable code block again another 2 seconds
// 'this' is referencing the Runnable object
handler.postDelayed(this, 2000);
}
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment