专注于Java Web开发 专注于HTML5前端

2020
04-11
安卓蓝牙通信服务端和客户端
作者:吉他和弦  围观148次  评论0条
服务端:
BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
判断蓝牙是否开启
BluetoothAdapter adapter = manager.getAdapter();
if(adapter.getState()!=BluetoothAdapter.STATE_ON) adapter.enable()
广播蓝牙服务
BluetoothLeAdvertiser advertiser = adapter.getBluetoothLeAdvertiser();
//blueTooth设置
AdvertiseSettings.Builder settingBuilder = new AdvertiseSettings.Builder();
settingBuilder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_POWER);
settingBuilder.setTimeout(0);
//data
AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
dataBuilder.setIncludeDeviceName(true);
advertiser.startAdvertising(settingBuilder.build(), dataBuilder.build(), advertiseCallback)
监听广播成功回调advertiseCallback-> onStartSuccess执行下面代码
gattServer = manager.openGattServer(mContext,gattServerCallback);//监听客户端连接接服务器回调
BluetoothGattService service = new BluetoothGattService(UUID.fromString("1-1-1-1-1"),BluetoothGattService.SERVICE_TYPE_PRIMARY);
//read
BluetoothGattCharacteristic gattCharacteristicRead = new BluetoothGattCharacteristic(UUID.fromString("2-2-2-2-2"),BluetoothGattCharacteristic.PROPERTY_READ,BluetoothGattCharacteristic.PERMISSION_READ);
BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(UUID.fromString("3-3-3-3-3"),BluetoothGattCharacteristic.PERMISSION_WRITE);
gattCharacteristicRead.addDescriptor(descriptor);
service.addCharacteristic(gattCharacteristicRead);
//write
BluetoothGattCharacteristic characteristicWrite=new BluetoothGattCharacteristic(UUID.fromString("4-4-4-4-4"),
BluetoothGattCharacteristic.PROPERTY_WRITE |BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_WRITE);
service.addCharacteristic(characteristicWrite);
gattServer.addService(service);
//监听服务器回调gattServerCallback->onConnectionStateChange
后面就是主要几个函数发送和接收信息了
onCharacteristicReadRequest
onCharacteristicWriteRequest
客户端:
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
//下判断蓝牙是否打开,与服务端一致
//监听扫描蓝牙设备的广播
BroadcastReceiver searchDevices = new BroadcastReceiver(){}
mBluetoothAdapter.startDiscovery();
//发现设备时
BluetoothDevice.ACTION_FOUND.equals(action)
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//判断是否是我们想要找的设备
device.getName().contains("OPPO")
//停止扫描并连接目标设备
mBluetoothAdapter.cancelDiscovery();
mBluetoothGatt = mydevice.connectGatt(mContext, false, mGattCallback); //mGattCallback为回调接
//mGattCallback->onConnectionStateChange
if(newState == BluetoothProfile.STATE_CONNECTED&&gatt.discoverServices())//执行到这里其实蓝牙已经连接成功了
{
trace("access");
}
else
{
trace("fail");
}
//执行cancelDiscovery后继续回调onServicesDiscovered
//这里开始获取服务的特征值,每个服务对应几个读和写特征值
gatt.getServices()
//注意如果要监听服务端的Noty,必须
mBluetoothGatt.setCharacteristicNotification(characteristic, true);
//这样有通知就可以在onCharacteristicChanged接收到

我要回复:

姓名:
邮箱: