在Android中使用Handler发送消息

在Android中使用Handler发送消息,android,multithreading,handler,message-queue,Android,Multithreading,Handler,Message Queue,亲爱的。我正在学习Android开发,我被处理器/循环器和MessageQueue困住了。 根据文档,处理程序能够向另一个线程发送消息并发布(可运行),因此我尝试了以下方法: 我有两个java文件,一个用于不同的类: public class MyThread extends Thread { public MyThread(String argument) { //save the arguments to some member attribute }

亲爱的。我正在学习Android开发,我被处理器/循环器和MessageQueue困住了。 根据文档,处理程序能够向另一个线程发送消息并发布(可运行),因此我尝试了以下方法:

我有两个java文件,一个用于不同的类:

public class MyThread extends Thread {
    public MyThread(String argument) {
        //save the arguments to some member attribute
    }

    @Override
    public void run() {
        //calculate something
        String result = doSomething();

        //now I need send this result to the MainActivity.
        //Ive tried this
        Bundle bundle = new Bundle();
        bundle.putString("someKey", result);
        Message msg = Message.obtain();
        msg.what = 2;
        msg.setData(bundle);

        //I hope this could access the Main Thread message queue
        new Handler(Looper.getMainLooper()).sendMessage(msg);
    }
}
我的主要活动是:

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstance) {
        //super and inflate the layout
        //use findViewById to get some View
    }

    //I think this could access the same MessageQueue as the thread did
    private Handler mHandler = new Hander() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 2) {
                //I thought the sendMessage invoked inside the Thread
                //would go here, where I can process the bundle and
                //set some data to a View element and not only Thread change
            }
        }
    }
}
由于阅读示例和文档时我无法理解它是如何工作的,因此我想简单解释一下如何从线程(不知道MainActivity)获取一些数据,并将其显示在Activity或Fragment内部的视图中


谢谢

在您的示例中,main是
Looper.getMainLooper()
,这意味着它会将消息发送到附加到UI线程的
处理程序,
MainActivity
正在UI线程中运行,它的处理程序名为
Handler
,因此消息将在该线程的
handleMessage
处接收


您可以阅读更多有关的内容,

我认为基本上您是通过实现在UI线程上创建了两个处理程序。这就是为什么在主要活动中你没有被召回


您可以尝试在MyThread中获取mHandler的引用,并对其调用sendMessage()。这样,您的作业就使用了单个处理程序。

从您开始MyThread的地方开始,当前从MainActivity内的按钮onClick开始。您是对的。我发现主线程已经有了自己的隐式处理程序。即使我创建了一个通过MainLooper的新处理程序(在线程内部),它也不是已经绑定到MainLooper的同一个处理程序。为了解决这个问题,我必须将主线程处理程序传递给MyThread并使用它发送消息。谢谢你的澄清。