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活動或片段內的視圖。
感謝
從你開始的位置開始MyThread – Rahul
當前從MainActivity中的按鈕的onClick。 –