Skip to content

Instantly share code, notes, and snippets.

@granoeste
Created June 18, 2011 13:15
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save granoeste/1033085 to your computer and use it in GitHub Desktop.
Save granoeste/1033085 to your computer and use it in GitHub Desktop.
[Android]Using the Handler and Lopper with HandlerThread
// With reference to the android.app.IntentService of the Android framework
// Member variable
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
// Handler Class
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// TODO
// Process the received message.
}
}
// Create the HandlerThread, and start
// Get the looper from the HandlerThread to the constructor of the Handler it.
public void onYourCreateMethod() {
HandlerThread thread = new HandlerThread("<Thread Name>");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
// Send a message using the Handler was created.
public void onYourMethod(Intent intent) {
Message msg = mServiceHandler.obtainMessage();
msg.what = <What>;
msg.obj = <Object>;
mServiceHandler.sendMessage(msg);
}
// To terminate the Handler
public void onYourDestroyMethod(Intent intent) {
mServiceLooper.quit();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment