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.
According to this page these steps are required:
Handler
object exactly on the thread you want to handle
messages.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.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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With