最近在做手机连接蓝牙血压计、血氧仪和血糖仪的开发,一般这样在设备端是不做任何操作的,只需在手机客户端发送指令达到数据传输。
一、蓝牙的连接
1.首先得判断手机是否支持蓝牙或者打开蓝牙吧,代码如下:
private BluetoothAdapter mBluetoothAdapter;
private BluetoothGatt mBluetoothGatt;
private List<BluetoothGattService> mGattServiceList;
……………………
BluetoothManager manager = (BluetoothManager) getSystemService("bluetooth");
mBluetoothAdapter = manager.getAdapter();
//判断蓝牙是否可用与是否打开了蓝牙
if(mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
tv_status.setText("please open your bluetooth first");
showOpenBtDialog(); //选择打开蓝牙对话框
}
2.打开系统蓝牙设置
/**
* 打开蓝牙对话框
*/
private void showOpenBtDialog() {
new AlertDialog.Builder(this)
.setMessage("please open your bluetooth")
.setPositiveButton("Yes", newDialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
// TODO Auto-generated method stub
dialog.cancel();
Intent intent = new Inteny(Settings.ACTION_BLUETOOTH_SETTINGS);
startActivity(intent);
}
}).show();
}
3.开启蓝牙后,启动扫描
/**
* 开始扫描
*/
private void startScan() {
if(!isScanning && !ifSucc && mBluetoothAdapter != null) {
tv_status.setText("Scanning...");
mBluetoothAdapter.startLeScan(mLeScanCallback);
isScanning = true;
}
}
/**
* 结束扫描
*/
private void stopScan() {
if(mBluetoothAdapter != null) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
isScanning = false;
}
}
/**
* 扫描设备回调
*/
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int paramAnonymousInt, byte[] paramAnonymousArrayOfByte) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Log.i("wsjInfo", "device name= " + device.getName());
if(device.getName() != null && device.getName().equals("MEDXING-BGM")) { //我这里的设备名称是这个
stopScan(); //找到设备停止扫描
mBluetoothGatt = device.connectGatt(BloodSugarActivity.this, false, mBluetoothGattCallback);
tv_status.setText("Connecting...");
}
}
});
}
};
4.蓝牙连接成功后,回调这个最重要了。
/**
* 蓝牙中央回调
*/
private BluetoothGattCallback mBluetoothGattCallback = new BluetoothGattCallback() {
@Override //接发数据
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
// Log.e("onCharacteristicChanged", "onDataChanged");
//获取到蓝牙设备发送的字节数组数据过来
byte[] res = characteristic.getValue();
for(int i=0; i < res.length; i++) {
Log.e("wsjInfo", "byte[" + i + "]=" + res[i]);
}
//具体的处理就看设备通讯协议
Message msg = mHandler.obtainMessage();
msg.what = WHAT_DATACHANGED;
msg.obj = res;
mHandler.sendMessage(msg);
}
@Override //连接状态改变
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
// Log.e("onConnectionStateChange", "st