Android蓝牙通讯(三)————蓝牙通讯的实现

移动开发 waitig 424℃ 百度已收录 0评论

在前两篇博客中大致介绍了蓝牙相关的基础知识,不了解的朋友可以查看前两篇博客:
Android蓝牙通讯(一)————蓝牙功能的相关权限
Android蓝牙通讯(二)————蓝牙的相关操作

在本篇博客中我将介绍如何实现两个蓝牙设备之间的通讯,蓝牙的通讯类似于socket的通讯,在蓝牙通讯中没有绝对的设备充当server角色,基本上就是发送连接请求的设备充当client角色,而server一般会在开辟一个子线程,在子线程中不断循环监测是否有client的请求连接,代码如下:

private class AcceptListener extends Thread {
        private BluetoothServerSocket mServerSocket;
        private BluetoothAdapter mAdapter;
        private BluetoothSocket mSocket;
        public AcceptListener() {
            mAdapter = BluetoothAdapter.getDefaultAdapter();
        }

        @Override
        public void run() {
            try {
                setState(STATE_LISTEN);
                mServerSocket = mAdapter.listenUsingInsecureRfcommWithServiceRecord("bluetooth",UUID_INSECURE);
                while (mState != STATE_CONNECTED && mState != STATE_CONNECTING){
                    mSocket = mServerSocket.accept();
                    if(mSocket != null){
                        setState(STATE_CONNECTING);
                        synchronized (BluetoothService.this){
                           connected(mSocket);
                        }
                    }
                }
            } catch (IOException e) {
            }
        }
    }

这是server在监听client的连接请求,在代码中一个AcceptListener 线程只会监听一个请求连接,只要连接成功,server将不再监听client的连接请求,代码也不接简洁,就不介绍了!

下面来看客户端的连接请求,代码如下:

private class ConnectThread extends Thread {
        private BluetoothSocket mClientSocket;
        private BluetoothDevice mDevice;
        public ConnectThread(BluetoothDevice device) {
            this.mDevice = device;
            try {
                mClientSocket = mDevice.createInsecureRfcommSocketToServiceRecord(UUID_INSECURE);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            boolean connected = false;
            int i = 0;
            do{
                try {
                    mClientSocket.connect();
                } catch (IOException e) {
                    connected = true;
                }
                i++;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }while(connected && i<10);
            connected(mClientSocket);
        }
    }

我们通过BluetootDevice获取一个BluetoothSocket,通过这个Socket发送连接请求,在代码中,我们尝试10次连接,如果十次连接都没有连接成功,也就不再连接了!连接成功之后,那么这个Socket我们就可以正常使用了,通过socket与服务器端进行通讯!!

信息发送代码:

private class DataThread extends Thread {

        private BluetoothSocket mDataSocket;
        private OutputStream mOut;
        private InputStream mIn;
        public DataThread(BluetoothSocket socket) {
            this.mDataSocket = socket;
            try {
                mIn = mDataSocket.getInputStream();
                mOut = mDataSocket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            setState(STATE_CONNECTED);
        }

        @Override
        public void run() {
            super.run();
            android.util.Log.e("zyq","read message ....");
            byte[] buffer = new byte[1024];
            int bytes;
            while (true) {
                try {
                    StringBuffer sb = new StringBuffer();
                    while((bytes = mIn.read(buffer)) != -1){
                        sb.append(new String(buffer,0,bytes));
                    }
                    Bundle data = new Bundle();
                    data.putString("bluetooth_message",sb.toString());
                    Message m = Message.obtain();
                    m.setData(data);
                    m.what = MainActivity.UPDATE_BLUETOOTH_MESSAGE;
                    mHandler.sendMessage(m);
                } catch (IOException e) {
                    android.util.Log.e("zyq","DataThread : e = "+e.getMessage());
                    setState(STATE_NONE);
                    BluetoothService.this.startListener();
                    break;
                }
            }
        }

        public void write(byte[] buffer) {
            try {
                mOut.write(buffer);
                mOut.flush();
            } catch (IOException e) {
            }
        }

        public void close(){
            try {
                if (mDataSocket != null) {
                    mDataSocket.close();
                }
                if(mOut != null){
                    mOut.close();
                }
                if(mIn != null){
                    mIn.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

通过Socket获取OutputStream和InputStream,通过使用输入/输出流进行消息的传递!在使用read方法时,没有有效的数据时会阻塞线程!!

实际测试可以进行简单的通讯,完整代码可以在GitHub上获取,有兴趣的朋友可以关注我一下,有什么问题大家相互讨论一下!!!

代码地址:Bluetooth Demo


本文由【waitig】发表在等英博客
本文固定链接:Android蓝牙通讯(三)————蓝牙通讯的实现
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (0)分享 (0)