【问题标题】:Managing bluetooth connection Android管理蓝牙连接 Android
【发布时间】:2014-02-19 01:17:50
【问题描述】:

我目前正在尝试将蓝牙 HC-05 模块与 Android 连接,以便通过模块将字节发送到 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

我在我们的代码中看到的不同之处主要是他确实 start()了他的 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;
                }
            }
        }

【问题讨论】:

    标签: android bluetooth arduino android-bluetooth


    【解决方案1】:

    您对线程的使用完全是错误的。

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

    因此,正如您所做的那样,在 线程对象的构造函数又错了。

    而且,由于您还没有 start()-ed 线程,因此套接字 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();
    

    否则什么都不会发生。

    【讨论】:

      【解决方案2】:

      我记得处理程序有类似的问题。那是很久以前的事了,所以我不记得每个细节,但它与mHandler.sendToTarget有关。我认为有一个 mHandler.dispatchMessage 方法(或类似的方法 - 我不在我的编程电脑上,所以我现在无法验证这一点)。 你应该试一试。

      【讨论】:

        【解决方案3】:

        你确定字符串“成功连接”确实接收到 arduino 吗?代码 sn -p 没有带出连接线程的 write 方法。请参考 android sdk 中的蓝牙聊天源代码。

        几个区域供您寻找:

        1) 连接线程在启动连接线程之前没有关闭。

        2) 常量 SUCCESS_CONNECT & MESSAGE_READ 的定义。它们是私有的,但可以从不同的类访问。在蓝牙聊天源中,它们被定义为公共的。

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

        Main_Activity.SUCCESS_CONNECT 
        Main_Activity.MESSAGE_READ. 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-27
          • 2011-12-23
          • 2015-10-25
          • 1970-01-01
          相关资源
          最近更新 更多