问题
I am using a Thread to do some BT tasks. I am trying to send a message to the UI thread so I can do UI work based on my BT thread. To do this I am using a Handler, but I don't know how to retrive the data that I send to my Handler.
To send data i use:
handler.obtainMessage(intCode).sendToTarget();
Where intCode is an int. My Handler looks like this.
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg){
Bundle data = msg.getData();
int code = data.getInt("what");
Log.d(LOG_TAG, "Msg: "+code);
}
}
But the value of code is never anything else than 0. How do i get the value sent when doing .obtainMessage(int)? Is the value not stored in a Bundle with the key "what"?
回答1:
You can set data in this format
While setting data
Message msg = new Message();
msg.obj = data which you want to set // for object data
Msg.arg1 = data which you want to set // for integer data
While getting data
String data = (String) msg.obj; // If object is of String
int integerData = msg.arg1;
msg.arg1 will pass only one data at a time you can also pass data in msg.arg2 they both are of integer types
回答2:
You can get Message data under the param Message in public boolean handleMessage(Message message)
. For example, to get arg1 in message, you can just:
mHandler = new Handler(this.getLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message message) {
switch (message.what){
case MY_MESSAGE_1:
int argument1 = message.arg1;
return true;
....
来源:https://stackoverflow.com/questions/17929310/get-what-parameter-from-handler-obtainmessage