今天开始写博客来记录我的工作学习成长,作为一个初学者,近期的一个工作是通过Android蓝牙4.0来实现与蓝牙设备的数据交换,下面就通过代码和文字来解释一下整个过程。
首先我要说明的是,我再项目中使用了一个开源库,我觉得不错,所有代码都是在该库基础上实现的,地址:https://github.com/litesuits/android-lite-bluetoothLE
下面进入正题
1,检查设备是否支持蓝牙4.0,和打开蓝牙
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "设备不支持BLE", Toast.LENGTH_SHORT).show();
finish();
}
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
2,搜索蓝牙4.0设备,该方法是搜索蓝牙设备SCAN_PERIOD事件,通过回调函数new PeriodScanCallback来处理结果,分为超时和找到蓝牙设备,自己可以在回调函数中作相应处理
/**
* scan devices for a while
*/
private void scanDevicesPeriod() {
mScanning = true;
this.startBluetoothProgressDialog("正在搜索蓝牙设备...");
showMessage.setText("正在搜索蓝牙设备...");
SampleGattAttributes.liteBluetooth.startLeScan(new PeriodScanCallback(SCAN_PERIOD) {
@Override
public void onScanTimeout() {
BluetoothSearchActivity.this.stopBluetoothProgressDialog();
mScanning = false;
handler1.sendEmptyMessage(3);
SampleGattAttributes.liteBluetooth.stopScan(null);
}
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
if(device != null && device.getName() != null && device.getName().startsWith("XXXX")){
bluetoothDevice = device;
deviceName.add(device.getName());
mDeviceName = device.getName();
mDeviceAddress = device.getAddress();
SampleGattAttributes.address