我知道这是一个很长的帖子,但请多多包涵:)的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