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 のソースを参考にコードを記述してみました。
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(); | |
} |
参考サイト
- throw Life - AndroidのHandlerとは何か?
- android情報まとめ @ ウィキ - メモ/Looper
- 勉強中: HandlerThread・Handler・Messageの使い方
- HandlerThreadとHandlerとLooperの関係 - 理系のためのTIPS集
- KMC Staff Blog:AndroidのLooperとHandlerの実装
- GPソフト Wiki - AndroidのHandlerとLooper
- HandlerとMessage - 別スレッドでのGUI操作 - 愚鈍人
- ThreadとHandlerでマルチスレッド処理化する « Tech Booster
0 件のコメント:
コメントを投稿