handleMessage函数未被调用

时间:2013-06-23 00:34:48

标签: java android multithreading bluetooth handler

我正在用Android应用程序帮助我的朋友,我不明白为什么我无法获得Handle函数,handleMessage()被调用。我目前正在尝试通过蓝牙进行通信,我有一个线程处理写入和处理读取的线程,所以我想我搞砸了某个地方。我真的不熟悉Thread,我想知道是否有人能发现我的错误!我知道写功能正常工作,因为我看到蓝牙芯片在编写下面的"$$$"代码后进入命令模式。

MainActivity:

public class MainActivity extends Activity{
....
    private final Handler mHandler = new Handler(){
            @Override
        public void handleMessage(Message msg) {
            System.out.println("in mHandler");//NOT CALLED
                switch (msg.what) {
                    case (MESSAGE_READING):
                    byte[] readBuf = (byte[])msg.obj;
                    String readMessage = new String(readBuf,0,msg.arg1);
                    System.out.println("READ: " + readMessage);
                    break;
                default:
                        System.out.println("default!");
                    break;
                }
            }
        };
        ...
     }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        mConnectThread = new ConnectThread(device, mHandler);
        mConnectThread.run();
        ListenerThread mListener = new ListenerThread(mConnectThread,mHandler);
        mListener.run();
    }

ConnectThread:

public class ConnectThread{

public final BluetoothSocket mmSocket;
public final BluetoothDevice mmDevice;
private final Handler mHandler;
public static ConnectedThread mConnectedThread;

public ConnectThread(BluetoothDevice device, Handler mHandler) {
    // Use a temporary object that is later assigned to mmSocket,
    // because mmSocket is final
    BluetoothSocket bs = null;
    mmDevice = device;

    // Get a BluetoothSocket to connect with the given BluetoothDevice
    try {
        // MY_UUID is the app's UUID string, also used by the server code
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard Serial Port Service ID
        bs = device.createRfcommSocketToServiceRecord(uuid);
    } catch (IOException e) {
        System.err.println("IOException in ConnectThread");
    }

    this.mHandler = mHandler;
    mmSocket = bs;
}

public void run() {
    //TODO Cancel discovery because it will slow down the connection

    try {
        // Connect the device through the socket. This will block
        // until it succeeds or throws an exception
        mmSocket.connect();
    } catch (IOException connectException) {
        // Unable to connect; close the socket and get out
        try {
            mmSocket.close();
        } catch (IOException closeException) { }
        return;
    }

    // Do work to manage the connection (in a separate thread)
    mConnectedThread = new ConnectedThread(mmSocket, mHandler);
    mConnectedThread.run();

}
...
}

ConnectedThread:

public class ConnectedThread extends Thread {
....
public void manageConnectedSocket() {

    byte[] buffer = new byte[1024];  // buffer store for the stream
    int bytes; // bytes returned from read()

    // Keep listening to the InputStream until an exception occurs
    while (true) {
        try {
            // Read from the InputStream
            bytes = mmInStream.read(buffer);
            System.out.println("Reading bytes.");
            status = MESSAGE_READING;
            // Send the obtained bytes to the UI activity
            Message msg = Message.obtain(mHandler, MESSAGE_READING, bytes, -1, buffer);
            mHandler.sendMessage(msg);
        } catch (IOException e) {
            System.err.println("Error reading input");
            break;
        }
        status = READY;
    }
}
...
}

ListenerThread:

public class ListenerThread extends Thread {

...

public final BluetoothSocket mmSocket;
private final Handler mHandler;
private final ConnectedThread mConnectedThread;

public ListenerThread(ConnectThread mConnectThread, Handler mHandler){
    this.mHandler = mHandler;
    mmSocket = mConnectThread.mmSocket;
    this.mConnectedThread = mConnectThread.getConnectedThread();
}

public void run(){
    while (true){
        if (getStatus() == READY){
            write("$$$".getBytes());
            break;
        }
    }
}
...
}

我看了几个关于handleMessage的其他问题,但他们没有帮助。有什么想法吗?

编辑:刚才意识到这是很多代码。基本上我将mHandler传递给我的不同主题,我认为这是一些不好的事情发生的地方。我有ConnectThreadConnectedThreadListenerThread。我正在寻找蓝牙的Android文档说在后台运行,因为一些调用(writereaddevice.connect())是阻塞调用。

1 个答案:

答案 0 :(得分:3)

我认为您的代码的问题在于您通过run()方法启动线程,这意味着您只需对对象执行run()方法。但您必须调用start()方法,该方法将启动新主题并自动调用您的run()方法。

以下是Thread.start()方法文档

的引用
  

使该线程开始执行; Java虚拟机调用此线程的run方法。