Created
June 18, 2011 13:15
-
-
Save granoeste/1033085 to your computer and use it in GitHub Desktop.
[Android]Using the Handler and Lopper with HandlerThread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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