2011年6月18日土曜日

HandlerThreadで、LooperとHandlerを使用する方法

メッセージキューの仕組みを実装しようとして、LooperやThread、Handlerを調べていたら、
HandlerThreadという便利なクラスがあったのでメモ

HandlerThread の概要
Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.

ルーパーを持つ新しいスレッドを開始するための便利なクラス。ルーパーは、ハンドラクラスを作成するために使用することができます。 start()を呼び出す必要があることに注意してください。

HandlerThreadはThreadを継承していて、内部にLooperを保持しています。
そのLooperを使って、Handlerのインスタンスを作成します。

android.app.IntentService のソースを参考にコードを記述してみました。

// 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();
}
view raw gistfile1.java hosted with ❤ by GitHub



参考サイト

0 件のコメント:

コメントを投稿