没有关于如何使用带有 4 个参数的 obtainMessage
方法编写处理程序的示例。
我尝试了几种方法,但仍然出现相同的错误。
Handler mHandler = new Handler() {
public final Message obtainMessage(int what,
int arg1, int arg2, Object obj) {
}
};
这显然是错误的,但考虑到没有任何示例可以从中获得帮助,我可以使用一些指导。
最佳答案
根据 this page需要这些步骤:
- 在您要处理的线程上创建
Handler
对象 消息。 - 使用
Handler.obtainMessage
从创建的Handler
获取一个Message
实例。无需在Handler
的所有者线程上执行此操作。它可以从任何其他线程完成。 - 使用
Handler.sendMessage
发送消息。
为了进一步详细说明该过程,这里有一个分为两部分的示例代码。第一个是示例 BluetoothThread
,其功能最少,只能发送一个虚构的文件。第二部分是使用上述线程的按钮单击处理程序。
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;
}
}
在主要 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));
}
关于android - 如何使用 obtainMessage 编写正确的处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24837548/