2017-08-08 109 views
1

Dears。我正在学习Android开发,并被卡在Handlers/Loopers和MessageQueue上。 根据文档处理程序都能够和的sendMessage后(Runnable接口)到另一个线程,所以我尝试了以下内容:使用Handler在Android中发送消息

我有两个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)被显示为int o活动或片段内的视图。

感谢

+0

从你开始的位置开始MyThread – Rahul

+0

当前从MainActivity中的按钮的onClick。 –

回答

1

我觉得基本上您创建从您实现UI线程2个处理器。这就是为什么在MainActivity中你没有被回叫。

您可以尝试在MyThread中获取mHandler的引用,并在其上调用sendMessage()。通过这种方式,您正在为您的工作使用单个处理程序。

+0

你说得对。我发现主线程已经有了它自己的隐式处理程序。 即使我创建了一个新的(在线程内)传递MainLooper,它与已经绑定到MainThread的Handler不是同一个Handler。 为了解决这个问题,我必须将MainThread Handler传递给MyThread并使用它来发送消息。 感谢您的澄清。 –

0

在您的例子主要是Looper.getMainLooper(),这意味着它会发送消息到其连接到UI线程,你的情况HandlerMainActivity在UI线程中运行,它有处理程序的Handler的名称,所以邮件将收到在handleMessage的。

你可以阅读更多关于LooperCommunicating with the UI ThreadHandler