我目前正在使用BLE将我的Android设备与另一个蓝牙设备连接。
问题是,如何扫描已连接的设备?
在我的第一种方法中,我没有在连接方法之前调用stopLeScan。
这对上述问题没有问题,但它导致ui中断(ui更新间隔太短),有时连接时间非常慢。
在我的应用程序在连接之前调用stopLeDevice之后,每个问题都已解决,但是出现了一个新问题。新问题是我无法再在scanResult上看到连接的设备。它仅显示断开连接的设备。我仍想监视我连接的设备。我怎么能实现这个目标呢?
答案 0 :(得分:0)
使用此类启动自动到新的BLE设备。
BLEScanner服务
In [29]: store.get_storer('df').table
Out[29]:
/df/table (Table(10,)) ''
description := {
"index": Int64Col(shape=(), dflt=0, pos=0),
"a": Int32Col(shape=(), dflt=0, pos=1),
"b": Int32Col(shape=(), dflt=0, pos=2),
"c": Int32Col(shape=(), dflt=0, pos=3)}
byteorder := 'little'
chunkshape := (3276,)
autoindex := True
colindexes := {
"a": Index(6, medium, shuffle, zlib(1)).is_csi=False,
"index": Index(6, medium, shuffle, zlib(1)).is_csi=False,
"c": Index(6, medium, shuffle, zlib(1)).is_csi=False,
"b": Index(6, medium, shuffle, zlib(1)).is_csi=False}
In [30]: type(store.get_storer('df').table.colindexes)
Out[30]: tables.table._ColIndexes
In [31]: type(store.get_storer('df').table.description)
Out[31]: tables.description.Description
现在用于检查BLE设备连接的回调类
public class BLEScanner extends Service {
private BluetoothAdapter mBluetoothAdapter;
private ArrayList<BluetoothDevice> mLeDevices;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLeDevices = new ArrayList<BluetoothDevice>();
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
startLeScan();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void startLeScan() {
scanLeDevice(true);
}
private void stopLeScan() {
scanLeDevice(false);
}
private void scanLeDevice(boolean enable) {
if (enable) {
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
if (!mLeDevices.contains(device)) {
mLeDevices.add(device);
connectToDevice(device);
}
}
};
private void connectToDevice(final BluetoothDevice device) {
if (device != null) {
Log.i("Tag", "Name: " + device.getAddress() + " Connecting");
if (device.getName() != null)
device.connectGatt(this.getApplicationContext(), false, new BluetoothCallBack(this.getApplicationContext(), BLEScanner.this));
}
}
@Override
public void onDestroy() {
super.onDestroy();
stopLeScan();
mLeDevices.clear();
}
public void removeDevice(BluetoothDevice mDevice) {
try {
if (mLeDevices != null && mLeDevices.size() > 0)
mLeDevices.remove(mDevice);
} catch (Exception e) {
e.printStackTrace();
}
}
}