Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a correct handler with obtainMessage?

There are no examples on how to write a handler using the obtainMessage method with 4 arguments coming in.

I've tried several ways, but still getting the same errors.

Handler mHandler = new Handler() {
    public final Message obtainMessage(int what, 
        int arg1, int arg2, Object obj) {

    }
};

This is obviously wrong, but I could use a little direction considering there aren't any examples to get help from.

like image 572
user3716005 Avatar asked Jul 19 '14 06:07

user3716005


1 Answers

According to this page these steps are required:

  1. Create the Handler object exactly on the thread you want to handle messages.
  2. Obtain a Message instance from the created Handler using Handler.obtainMessage. There is no need for this action to be performed on the Handler's owner thread. It can be done from any other thread.
  3. Send the message using Handler.sendMessage.

To further elaborate the process, here is a sample code in two sections. First is a sample BluetoothThread with minimal functionality to just send an imaginary file. The second section is a button click handler which uses the said thread.

public class BluetoothThread extends Thread {
    private Handler mHandler;

    public static final SEND_CODE = 1;
    public static final QUIT_CODE = 2;

    @Override
    public void run() {
        Looper.prepare();

        mHandler = new Handler() {
          @Override
          public void handleMessage(Message msg) {
            if (msg.what == SEND_CODE) {
                // Send the file using bluetooth
              }
            else if(msg.what == QUIT_CODE) {
              Looper.quitSafely();
            }
          }

        Looper.loop();
    }

    public Handler getThreadHandler() {
      return mHandler;
    }
}

And in the main activity:

public void ButtonClicked(View v) {
  BluetoothThread thread = new BluetoothThread();
  thread.Start();

  Handler hnd = thread.getThreadHandler();
  hnd.sendMessage(hnd.obtainMessage(BluetoothThread.SEND_CODE, 0, 0, null));
}
like image 98
Klaus Avatar answered Sep 24 '22 08:09

Klaus