AndroidManifest.xml中添加如下权限
<!-- 蓝牙搜索配对 --> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH_SCAN" /> <!-- 蓝牙的开启 --> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
MainActivity.java文件修改如下 public static final UUID UUID_CLIENT = UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb"); public static final UUID SERVICE_UUID = UUID_CLIENT; public static String SERV_UUID = ("0000ffe0-0000-1000-8000-00805f9b34fb"); public static final UUID UUID_WRITE = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb"); public static String UUID_READ = ("0000ffe1-0000-1000-8000-00805f9b34fb"); public static String UUID_NOTE_STR = ("00002902-0000-1000-8000-00805f9b34fb"); public static UUID UUID_NOTE = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
class中声明:
public String deviceAddress = "F7:39:C9:D4:70:F1"; // 目标蓝牙设备的MAC地址
onCreate中连接:
final BluetoothManager bluetoothManager =(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
bluetoothAdapter.enable();
device = bluetoothAdapter.getRemoteDevice (deviceAddress);
bluetoothGatt = device.connectGatt(this, false, gattCallback);
gattCallback 很重要,在需要的地方需要重写实现一些方法
直接通过mac地址连接设备,需要手机的设备提前连接一次,比如用nRF Connect工具