私は、これは長い記事ですけど、私と一緒に負担してください:)AndroidのUIスレッドと子スレッドの通信
現在、私は、メインUIスレッドに、子スレッドからの通信にHandlerクラスを使用していて、私は他の方向(メインスレッドから子スレッドへ)のメッセージのメッセージキューの実装を使用しています。
子ノードがメッセージの送信先を知る方法は次のとおりです。メインスレッドでは、ハンドラオブジェクトを作成した後、私自身のメッセージキューを介して子への参照を送信し、子スレッドは参照値したがって、メッセージをアクティビティに送信する方法がわかります。
私のアプリケーションには複数のアクティビティがあり、それぞれが同じ子スレッドと通信する必要があります。 1つのアクティビティで作成したHandlerオブジェクトは次のアクティビティでは有効ではないので、新しいアクティビティが作成されるたびに(ユーザーがアクティビティ間で変更するたびに)、ハンドラオブジェクトを作成するたびに以前とまったく同じ方法で、子スレッドへの参照を送信します。
私の質問です:
これは適切な方法ですか? これを行う簡単な方法はありますか?子ノードから複数のアクティビティへの通信は?たとえば、シングルトンクラスなどを使用する以外は、カスタムキューを使用するたびにリファレンスを送信せず、シングルトンの変数を更新します。要求されるようにここで
EDIT
は、いくつかのコードです:
すべての活動ののonCreateメソッドでは、私は次のようにします。
...
//Create the main handler on the main thread so it is bound to the main thread's message queue.
createHandler();
//Send to the controller the msg handler of the UI thread
//Create messenger of appropriate type
Messenger mess = new Messenger(_MSGHANDLER_);
//Add the handler
mess.addContent(_HANDLERTAG_, mMainHandler);
//Add the name of this activity
mess.addContent(_ACTIVITYNAMETAG_, "RemyLoginActivity");
//Add the message to the controller's queue
controller.enqueue(mess)
...
関数のcreateHandlerは、ハンドラオブジェクトを作成し、特定のコールバック関数をアタッチします。
//Create the handler on the main thread so it is bound to the main thread's message queue
private void createHandler()
{
//Create the main handler on the main thread so it is bound to the main thread's message queue.
mMainHandler = new Handler()
{
public void handleMessage(Message msg)
{
//Get the messenger from the message
Messenger mess = (Messenger)msg.obj;
Log.i("Remy", "ActivityMainMenu::Message from Controller: " + mess.type());
switch(mess.type())
{
default: Log.i("Remy","OUPS::createHandler::Could not understand queue message type: " + mess.type());
break;
}
}
};
}
、最終的には、コントローラは、ハンドラがそれを参照する受信したときにそれを格納し、それはそうのようなメッセージを送信した子スレッドです:
activityHandler.sendMessage(msg);
私は忘れていないと思っています何か。
あなたはurコードを貼り付けることができますか? –
確かに、Edit pls – AndreiBogdan