需要的权限
<uses-permission android:name=”android.permission.BLUETOOTH” />
<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN” />
串口协议UUID
String SPP_UUID = “00001101-0000-1000-8000-00805F9B34FB”;
需要监听的相关广播
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND);
intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(searchDevices, intent);
获取蓝牙适配器
btAdapt = BluetoothAdapter.getDefaultAdapter();
蓝牙未打开时,调用系统打开蓝牙提示
if (btAdapt != null && btAdapt.isEnabled() == false) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, RQ_CODE_OPEN_BT);
return;
}
当然,你也可以不使用系统的打开蓝牙提示而直接打开蓝牙
btAdapt.enable();
关闭蓝牙
btAdatp.disable();
调用系统蓝牙设置
Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
startActivity(intent);
获取绑定设备列表:
Set<BluetoothDevice> pairedDevices = btAdapt.getBondedDevices();
和指定蓝牙设备建立socket连接
private void connect(BluetoothDevice btDev) { UUID uuid = UUID.fromString(SPP_UUID); try { btSocket = btDev.createRfcommSocketToServiceRecord(uuid); MyLog.i("开始连接..."); if (btSocket != null) { btSocket.connect(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
读取数据
private readData(){ InputStream is = null; byte[] buffer = new byte[1024]; InputStream is = null; try { is = BTConfigActivity.btSocket.getInputStream(); // 得到蓝牙数据输入流 num = is.read(buffer); // 读入数据 is.close(); } catch (IOException e) { } }
一般读取数据可开一线程循环读取,建立连接的一方蓝牙一次发送的数据,另一方可能分多次接收数据,这里需要注意处理。如果使用循环处理,可以使用InputStream的available()方法判断可以读取的字节流的长度从而判断是否有数据输入。
发送数据
private void sendData(byte[] cmd){ try { OutputStream os = BTConfigActivity.btSocket.getOutputStream(); // 蓝牙连接输出流 os.write(cmd); } catch (IOException e) { } }