公司有一项目,需要用到蓝牙通信。写这篇文章的目的,是记录下开发过程。
开发分为2个阶段:
1.连接蓝牙
连接蓝牙,需要使用到BluetoothSocket。
/** * 连接蓝牙线程 * * @author hhh * date 2015-12-17 */ private class BTConnectThread extends Thread { private final BluetoothSocket mmSocket; @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1) public BTConnectThread(BluetoothDevice device) { BluetoothSocket tmp = null; try { UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID); //创建蓝牙socket } catch (Exception e) { e.printStackTrace(); } mmSocket = tmp; } public void run() { try { mmSocket.connect(); } catch (IOException e) { try { mmSocket.close(); } catch (IOException e2) { e2.printStackTrace(); } BTstop(); return; } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
2.通信
在连接蓝牙成功后,方可进行蓝牙通信
/** * 蓝牙连接成功 * * @author hhh * date 2015-12-17 */ public synchronized void BTconnected(BluetoothSocket socket) { if (mBTConnectThread != null) { mBTConnectThread.cancel(); mBTConnectThread = null; } if (mBTConnectedThread != null) { mBTConnectedThread.cancel(); mBTConnectedThread = null; } mBTConnectedThread = new BTConnectedThread(socket); mBTConnectedThread.start(); } /** * 蓝牙连接成功 * * @author hhh * date 2015-12-17 */ private class BTConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public BTConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); BTstop(); } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { byte[] buffer = new byte[1024]; int bytesread; while (true) { try { //接收蓝牙信息(pandora) bytesread = mmInStream.read(buffer); byte[] tempdata = new byte[bytesread]; System.arraycopy(buffer, 0, tempdata, 0, bytesread); } catch (IOException e) { BTstop(); break; } } } public void write(byte[] buffer) { try { mmOutStream.write(buffer); } catch (IOException e) { e.printStackTrace(); } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
/** * 发送数据到蓝牙 * * @param buffer byte[]数组 * @author hhh * date 2015-12-17 */ public void SendDataToBluetooth(byte[] buffer) { BTConnectedThread btConnectedThread; synchronized (this) { if (mBTState != STATE_CONNECTED) return; btConnectedThread = mBTConnectedThread; } btConnectedThread.write(buffer); }