2017-08-08 107 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