Reputation: 303
Dears. Im studying Android development and I'm stuck on Handlers/Loopers and MessageQueue. According to documentation, Handlers are able to sendMessage and post(Runnable) to another thread, so I've tried the following:
I have two java files, one for a different class:
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);
}
}
And my Main Activity:
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
}
}
}
}
Since I could not understand how it really works reading the examples and documentation, I'd like a simple explanation in how can I get some data from a Thread (which does not know the MainActivity) to be displayed into a View inside Activity or Fragment.
Thanks
Upvotes: 2
Views: 9705
Reputation: 178
I think basically you created 2 handlers on the UI thread from your implementation. That is why in the MainActivity you didn't get called back.
You can try get a reference of the mHandler in the MyThread, and call sendMessage() on it. In this way, you are using single handler for your job.
Upvotes: 3
Reputation: 11622
In your example main is Looper.getMainLooper()
, this means it will send the message to the Handler
which is attached to the UI thread, In your case, MainActivity
is running in UI thread and it has Handler in the name of Handler
so the message will receive at handleMessage
of that.
You can read more about Looper, Communicating with the UI Thread, Handler
Upvotes: 0