Search code examples
androidmultithreadingbundlehandlermessage

Get what parameter from Handler.obtainMessage()


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"?


Solution

  • 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