Android 2.1的:在一个活动Muliple处理程序程序、Android、Muliple

2023-09-07 09:48:03 作者:め  太拿自己当回事

我有一个以上的处理程序的一个活动。我创建了的onCreate()主要活动的所有的处理程序。我的理解是的handleMessage()每个处理程序的方法永远不会被调用在同一时间,因为所有的信息都放在同一个队列(活动线程MessageQueue)。因此,它们将在其中被放入队列的顺序被执行。他们还将在主要活动的线程中执行。它是否正确 ?

 公共无效的onCreate(){

this.handler1 =新的处理程序(){
@覆盖
公共无效的handleMessage(信息MSG){

                            //操作1:instanceVariable1一些操作
super.handleMessage(MSG);
}
};

this.handler2 =新的处理程序(){

@覆盖
公共无效的handleMessage(信息MSG){
                            //操作2:instanceVariable1一些操作
super.handleMessage(MSG);
}

};

this.handler3 =新的处理程序(){
@覆盖
公共无效的handleMessage(信息MSG){
                            //操作3:instanceVariable1一些操作
super.handleMessage(MSG);

}
};
}
 

解决方案

从文档当你创建一个新的处理程序,它被绑定到创建它的线程的线程/消息队列 - 从这一点上,这将提供信息和可运行到消息队列并执行他们,因为他们出来的消息队列。

所以,你是对的,他们将在顺序运行,你排队他们在UI线程(因为你要在的onCreate创建它们)。

I've more than one Handlers in an Activity. I create all the handlers in the onCreate() of the main activity. My understanding is the handleMessage() method of each handler will never be called at the same time because all messages are put in the same queue (the Activity thread MessageQueue). Therefore, they will be executed in the order in which are put into the Queue. They will also be executed in the main activity thread. Is this correct ?

 public void onCreate() {

this.handler1 = new Handler() {
@Override
public void handleMessage(Message msg) {

                            //operation 1 : some operation with instanceVariable1
super.handleMessage(msg);
}
};

this.handler2 = new Handler() {

@Override
public void handleMessage(Message msg) {
                            //Operation 2: some operation with instanceVariable1
super.handleMessage(msg);
}

};

this.handler3 = new Handler() {
@Override
public void handleMessage(Message msg) {
                            //Operation 3: some operation with instanceVariable1
super.handleMessage(msg);

}
};
}
HD2最新新闻动态 手机中国第2页

解决方案

From the docs "When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue."

So you're right, they will run in the order that you queue them on the UI thread (since you are going to create them in onCreate).