管理安卓蓝牙连接

3
我目前正在尝试连接一个蓝牙HC-05模块和Android设备,以便通过模块向Android设备发送字节。我从这里几乎直接抄袭了一些代码,链接如下: http://developer.android.com/guide/topics/connectivity/bluetooth.html#ManagingAConnection 这是主程序。我遇到的问题是mhandler没有接收到MESSAGE_READ案例,这意味着我没有从模块接收数据。我想知道需要做什么才能将数据发送到运行MESSAGE_READ案例的地方?到目前为止,该程序已将设备配对并向我的arduino发送“连接成功”。
这是另一个之前有人提出的问题,他可能比我表达得更好,但没有得到答案,所以我想我不是唯一一个遇到这个问题的人。 https://stackoverflow.com/questions/20088856/no-data-buffered-from-bluetooth-module 我们代码之间的区别主要在于他启动了connectedThread()。感谢您的帮助!
public class Main_Activity extends Activity implements OnItemClickListener {

ArrayAdapter<String> listAdapter;

ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
IntentFilter filter;
BroadcastReceiver receiver;
String tag = "debugging";
Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        Log.i(tag, "in handler");
        super.handleMessage(msg);
        switch(msg.what){
        case SUCCESS_CONNECT:
            // DO something
            ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
            //Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
            String s = "successfully connected";
            connectedThread.write(s.getBytes());                
            Log.i(tag, "connected");

            break;
        case MESSAGE_READ:
            byte[] readBuf = (byte[])msg.obj;
            String string = new String(readBuf);
            Toast.makeText(getApplicationContext(), string, 0).show();              
            break;  

        }
    }

};

以下是应该将处理程序发送到上游的代码:

private class ConnectThread extends Thread {

        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            // Use a temporary object that is later assigned to mmSocket,
            // because mmSocket is final
            BluetoothSocket tmp = null;
            mmDevice = device;
            Log.i(tag, "construct");
            // Get a BluetoothSocket to connect with the given BluetoothDevice
            try {
                // MY_UUID is the app's UUID string, also used by the server code
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) { 
                Log.i(tag, "get socket failed");

            }
            mmSocket = tmp;
        }

        public void run() {
            // Cancel discovery because it will slow down the connection
            btAdapter.cancelDiscovery();
            Log.i(tag, "connect - run");
            try {
                // Connect the device through the socket. This will block
                // until it succeeds or throws an exception
                mmSocket.connect();
                Log.i(tag, "connect - succeeded");
            } catch (IOException connectException) {    Log.i(tag, "connect failed");
                // 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)

            mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
        }



        /** Will cancel an in-progress connection, and close the socket */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }

    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer;  // 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
                    buffer = new byte[1024];
                    bytes = mmInStream.read(buffer);
                    // Send the obtained bytes to the UI activity
                    mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();

                } catch (IOException e) {
                    break;
                }
            }
        }
3个回答

1

你使用线程的方式是错误的。

创建线程对象并不会启动一个物理线程!

因此,在线程对象的构造函数中放置一个可能很慢的套接字创建函数是错误的。

而且,由于你没有调用start()方法来启动线程,socket的connect()方法从未被调用!

请尝试以下方法:

class ConnectThread extends Thread {

     public ConnectThread(BluetoothDevice device) {
            // nothing long running here!
     }

     public void run() {
         device.createRfcommSocketToServiceRecord(MY_UUID);

         // followed by connect() etc.
     }
}

记得通过调用来激活线程。
  connectedThread.start();

否则什么都不会发生。

0

我记得我以前也遇到过类似的处理程序问题。那是很久以前的事了,所以我不记得所有的细节,但与mHandler.sendToTarget有关。我想还有一个mHandler.dispatchMessage方法(或类似的 - 我现在不在我的编程电脑上,所以无法立即验证)。你应该试试。


0

你确定字符串“successfully connected”确实被接收到Arduino了吗?代码片段没有展示connected线程的write方法。请参考Android SDK中提供的bluetoothchat源代码。

以下是你需要查找的几个区域:

1)在启动connected线程之前,connect线程没有关闭。

2)常量SUCCESS_CONNECT和MESSAGE_READ的定义。它们是私有的,但是从不同的类中访问。在bluetoothchat源代码中,它们被定义为public。

此外,在从不同的类中引用这些常量时,我们需要引用它们被定义的类,即如下所示引用:

Main_Activity.SUCCESS_CONNECT 
Main_Activity.MESSAGE_READ. 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接