</pre>第一次写博客,写得不好还请大家见谅。<p></p><p></p><p><span style="white-space:pre"></span>最近实验室老师有个婴儿车的项目,其中涉及蓝牙通讯的东西,用的是蓝牙4.0,对比下来,跟2.0相差太远了,我也就开始学习使用蓝牙4.0。</p><p></p><p></p><p><span style="white-space:pre">1. </span>第一步,当然是蓝牙搜索了,在此之前,我们需要先检查一下手机的蓝牙设备:</p><p></p><pre name="code" class="java"><span style="white-space:pre"> </span>if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
<span style="white-space:pre"> </span>Toast.makeText(this,"没有蓝牙", Toast.LENGTH_SHORT).show();
finish();
<span style="white-space:pre"> </span>}
2. 初始化一个蓝牙适配器:
<span style="white-space:pre"> </span>final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
<span style="white-space:pre"> </span>// 检查是否支持蓝牙的设备。
<span style="white-space:pre"> </span>if (mBluetoothAdapter == null) {
<span style="white-space:pre"> </span>Toast.makeText(this,"设备不支持", Toast.LENGTH_SHORT).show();
<span style="white-space:pre"> </span> finish();
<span style="white-space:pre"> </span> return;
<span style="white-space:pre"> </span>}
开始搜索蓝牙:
<span style="white-space:pre"> </span>private void scanLeDevice(final boolean enable) {
if (enable) {
//停止后一个预定义的扫描周期扫描。
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
bar.setVisibility(View.GONE);
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, 10000);
bar.setVisibility(View.VISIBLE);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
bar.setVisibility(View.GONE);
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
<span style="white-space:pre"> </span>}
10秒后停止扫描,
invalidateOptionsMenu()为声明选项菜单已经改变,在下一次显示时将调用onCreateOptionsMenu(Menu)
扫描时传入一个回调 BluetoothAdapter.LeScanCallback,扫描到设备将通过回调返回设备数据
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
HashMap<String, Object> map = new HashMap<String, Object>();
Log.e("a", "RSSI=:"+rssi+"");
map.put("name", device.getName());
map.put("andrass",device.getAddress());
map.put("device", device);
listItem.add(map);
Log.e("a","发现蓝牙"+device.getAddress()+"状态"+device.getBondState()+"type"+device.getType()+device.describeContents());
}
});
}
};
3. 连接蓝牙
在得到onLeScan()中得到device,这里我们要直接连接设备,所以设置为自动连接
BluetoothGatt mBluetoothGatt = device.connectGatt(context, false, mGattCallback);
这里我们得到中央BluetoothGatt了,可以对周边进行各种交互了,如:
mBluetoothGatt.disconnect()//断开连接
mBluetoothGatt.connect()//连接设备
mBluetoothGatt.readRemoteRssi()//读取设备的rssi值
BLE设备之间的数据传输是靠BluetoothGattCharacteristic实现的,在发送数据前,需要先设置的characteristic的值为你要发送的数据str:
characteristic.setValue(str);//给BluetoothGattCharacteristic设置值
mBluetoothGatt.writeCharacteristic(characteristic);//发送数据