宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

需要的权限

<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.addActionBluetoothDevice.ACTION_FOUND);
  intent.addActionBluetoothDevice.ACTION_BOND_STATE_CHANGED);
  intent.addActionBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
  intent.addActionBluetoothAdapter.ACTION_STATE_CHANGED);
  registerReceiversearchDevices, intent);

获取蓝牙适配器

btAdapt = BluetoothAdapter.getDefaultAdapter);

蓝牙未打开时,调用系统打开蓝牙提示

if btAdapt != null && btAdapt.isEnabled) == false) {
   Intent intent = new IntentBluetoothAdapter.ACTION_REQUEST_ENABLE);
   startActivityForResultintent, RQ_CODE_OPEN_BT);
   return;
  }

当然,你也可以不使用系统的打开蓝牙提示而直接打开蓝牙

btAdapt.enable);

关闭蓝牙

btAdatp.disable);

调用系统蓝牙设置

Intent intent = new IntentSettings.ACTION_BLUETOOTH_SETTINGS);
startActivityintent);

获取绑定设备列表:

Set<BluetoothDevice> pairedDevices = btAdapt.getBondedDevices);

和指定蓝牙设备建立socket连接

private void connectBluetoothDevice btDev) {
        UUID uuid = UUID.fromStringSPP_UUID);
        try {
            btSocket = btDev.createRfcommSocketToServiceRecorduuid);
            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.readbuffer); // 读入数据
        is.close);
   } catch IOException e) {
    }
}

一般读取数据可开一线程循环读取,建立连接的一方蓝牙一次发送的数据,另一方可能分多次接收数据,这里需要注意处理。如果使用循环处理,可以使用InputStream的available)方法判断可以读取的字节流的长度从而判断是否有数据输入。

发送数据

private void sendDatabyte[] cmd){
try {
    OutputStream os = BTConfigActivity.btSocket.getOutputStream); // 蓝牙连接输出流
        os.writecmd);
    } catch IOException e) {
    }
}