zoukankan      html  css  js  c++  java
  • Bluetooth篇 开发实例之九 和蓝牙模块通信

    首先,我们要去连接蓝牙模块,那么,我们只要写客户端的程序就好了,蓝牙模块就相当于服务端。

    连接就需要UUID。

    #蓝牙串口服务
    SerialPortServiceClass_UUID = ‘{00001101-0000-1000-8000-00805F9B34FB}’

    private UUID mUuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    第一步:

    首先要连接设备。这个参考Android Developer的例子来写:Android Developer -- Bluetooth篇 开发实例之二 连接设备

    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;
     
            // 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) { }
            mmSocket = tmp;
        }
     
        public void run() {
            // Cancel discovery because it will slow down the connection
            mBluetoothAdapter.cancelDiscovery();
     
            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)
            manageConnectedSocket(mmSocket);
        }
     
        /** Will cancel an in-progress connection, and close the socket */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }
    View Code

    代码:

        /**
         * 蓝牙客户端程序Socket,链接蓝牙服务器
         * 
         * @author THINK
         * 
         */
        private class BtClientThread extends Thread {
            private BluetoothSocket btSocket; // 链接的Socket
            private BluetoothAdapter btAdapter; // 蓝牙适配器,构造方法传入该值
    
            /**
             * 构造方法
             * 
             * @param bluetoothAdapter
             * @param btDevice
             * @param uuid
             */
            public BtClientThread(BluetoothAdapter btAdapter, BluetoothDevice btDevice, UUID uuid) {
                BluetoothSocket tmp = null;
                this.btAdapter = btAdapter;
                try {
                    tmp = btDevice.createRfcommSocketToServiceRecord(uuid);
                } catch (IOException e) {
                    Log.d("h_bl", "BtClientThread不能获取到BluetoothSocket");
                    e.printStackTrace();
                }
                btSocket = tmp;
            }
    
            /**
             * 启动子线程去链接
             */
            public void run() {
                Log.d("h_bl", "BtClientThread进入线程");
                // 链接时,蓝牙适配器要先取消搜索
                btAdapter.cancelDiscovery();
                try {
                    // 通过socket链接设备时,会阻塞线程,直到成功,或者抛出异常。
                    btSocket.connect();
                } catch (IOException connectException) {
                    Log.d("h_bl", "BtClientThread通过socket链接设备失败");
                    // 不能链接设备时,就关闭socket的,并退出。
                    try {
                        btSocket.close();
                    } catch (IOException closeException) {
                        Log.d("h_bl", "BtClientThread不能正常关闭socket");
                    }
                    return;
                }
                // Do work to manage the connection (in a separate thread)
                bConnectedThread = new BTConnectedThread(btSocket); // 当链接上蓝牙服务时
                bConnectedThread.start();
                Log.d("h_bl", "BtClientThread连接上设备了");
            }
    
            /**
             * 将取消正在进行的连接,并关闭套接字
             */
            public void cancel() {
                try {
                    btSocket.close();
                } catch (IOException e) {
                }
            }
        }

     第二步:

     管理连接。这个参考Android Developer的例子来写:Android Developer -- Bluetooth篇 开发实例之三 管理连接

    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 = 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);
                    // Send the obtained bytes to the UI Activity
                    mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();
                } catch (IOException e) {
                    break;
                }
            }
        }
     
        /* Call this from the main Activity to send data to the remote device */
        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) { }
        }
     
        /* Call this from the main Activity to shutdown the connection */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }
    View Code

     代码:

       /**
         * 蓝牙连接线程
         * 
         * @author THINK
         * 
         */
        private class BTConnectedThread extends Thread {
            private BluetoothSocket mmSocket;
            private InputStream mmInStream;
            private OutputStream mmOutStream;
    
            public BTConnectedThread(BluetoothSocket socket) {
                mmSocket = socket;
                InputStream tmpIn = null;
                OutputStream tmpOut = null;
                try {
                    tmpIn = socket.getInputStream();
                    tmpOut = socket.getOutputStream();
                } catch (IOException e) {
                    Log.d("h_bl", "socket.getInputStream()或者socket.getOutputStream()异常");
                }
                mmInStream = tmpIn;
                mmOutStream = tmpOut;
            }
    
            public void run() {
                Log.d("h_bl", "run()");
                byte[] buffer = new byte[30]; // buffer store for the stream
                int bytes; // bytes returned from read()
                // 读程序要一直开启,死循环
                while (true) {
                    Log.d("h_bl", "run()2");
                    try {
                        Log.d("h_bl", "run()3");
                        // Read from the InputStream
                        bytes = mmInStream.read(buffer);
                        Log.d("h_bl", "返回的数据的长度为" + bytes);
                        String readString = new String(buffer);
                        Log.d("h_bl", "返回的数据为" + readString);
                        //这边需要在处理
                    } catch (IOException e) {
                        break;
                    }
                }
            }
    
            /* Call this from the main Activity to send data to the remote device */
            public void write(byte[] bytes) {
                try {
                    mmOutStream.write(bytes);
                    //如果在用流的时候,没有用flush()这个方法,很多情况下会出现流的另一边读不到数据的问题,特别是在数据特别小的情况下
                    mmOutStream.flush();
                } catch (IOException e) {
                }
            }
    
            /* Call this from the main Activity to shutdown the connection */
            public void cancel() {
                try {
                    mmSocket.close();
                } catch (IOException e) {
                }
            }
        }

    以上,写不好,扩展性太差,有些,该判断的没有判断。

    需要参考Bluetooth Chat sample app来写。

    UUID参考地址:http://blog.csdn.net/wletv/article/details/8957612

  • 相关阅读:
    light oj 1105 规律
    light oj 1071 dp(吃金币升级版)
    light oj 1084 线性dp
    light oj 1079 01背包
    light oj 1068 数位dp
    light oj 1219 树上贪心
    light oj 1057 状压dp TSP
    light oj 1037 状压dp
    矩阵快速幂3 k*n铺方格
    矩阵快速幂2 3*n铺方格
  • 原文地址:https://www.cnblogs.com/H-BolinBlog/p/5546681.html
Copyright © 2011-2022 走看看