Skip to content

Instantly share code, notes, and snippets.

@charlieCollins
Last active December 10, 2015 14:28
Show Gist options
  • Save charlieCollins/4447502 to your computer and use it in GitHub Desktop.
Save charlieCollins/4447502 to your computer and use it in GitHub Desktop.
Android two thread (main and back) examples for review.
//
// EXAMPLE METHOD 1
//
// member var
private final Looper backLooper; // background looper, only used here internally
//inside onCreate or ctor, etc
HandlerThread thread = new HandlerThread("BackLooper", Thread.NORM_PRIORITY);
thread.start();
backLooper = thread.getLooper();
// helpers to use it back and main
private void runOnBackThread(Runnable r) {
new Handler(backLooper).post(r);
}
private void runOnMainThread(Runnable r) {
new Handler(Looper.getMainLooper()).post(r);
}
//
// EXAMPLE METHOD 2
//
// I've also seen this, which seems cleaner, but effectively is the same thing (from square code samples, like tape)
private static final Handler MAIN_THREAD = new Handler(Looper.getMainLooper());
MAIN_THREAD.post(RunnableHere);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment