我知道這是一個很長的帖子,但請多多包涵:)的Android UI線程和子線程通信
我目前使用的處理程序類從一個子線程的主UI線程進行溝通,並我正在使用我的消息隊列實現消息在另一個方向(從主線程到子線程)。
子節點知道在哪裏發送消息的方式是:在主線程中,在創建Handler對象之後,我通過自己的消息隊列發送它對孩子的引用,然後子線程將參考值從而知道如何將消息發送給活動。
但是,我在我的應用程序中有多個活動,並且每個人都需要與同一個子線程進行通信。我在一個Activity中創建的Handler對象在下一個Activity中無效,所以我每次創建一個新活動時(每當用戶在活動之間改變時),每次創建一個Handler對象,和以前完全一樣,併發送它對子線程的引用。
我的問題是:
這是做這件事的正確方法? 有沒有更簡單的方法來做到這一點?從子節點通信到多個活動?除了使用單例類或類似的東西,所以我不會每次通過我的自定義隊列發送引用,而是更新單例中的變量。
EDIT
下面是一些代碼,作爲請求:
在每一個活動的onCreate方法i執行以下操作:
...
//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);
希望我沒有忘記一些東西。
你能粘貼你的代碼嗎? – 2012-02-22 10:35:16
當然,檢查編輯請求 – AndreiBogdan 2012-02-22 10:45:17