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。 –