我目前正在使用BLE将我的android设备与另一个蓝牙设备连接起来。
问题是,我如何扫描已连接的设备?
在我的第一种方法中,我没有在connection方法之前调用stopLeScan。
这对上面的问题没有问题,但它导致ui中断( ui更新间隔太短),有时连接时间非常非常慢。
在我让我的应用在连接前调用stopLeDevice之后,所有的问题都已经解决了,但又出现了一个新的问题。新的问题是,我在scanResult上看不到已连接的设备。它只显示断开连接的设备。我仍然想监控我的连接设备。我怎么才能得到这个呢?
发布于 2016-08-03 14:40:52
使用此类启动自动转到新的BLE设备。
BLEScanner服务
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();
}
}
}现在回调类检查BLE设备是否连接
public class BluetoothCallBack extends BluetoothGattCallback {
private BLEScanner mServiceObject;
public BluetoothCallBack(Context mContext, BLEScanner mServiceObject) {
this.mServiceObject = mServiceObject;
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.i("Tag", "CONNECTED DEVICE: " + gatt.getDevice().getAddress());
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.e("Tag", "DISCONNECTED DEVICE: " + gatt.getDevice().getAddress());
gatt.disconnect();
gatt.close();
mServiceObject.removeDevice(gatt.getDevice());
}
}
}https://stackoverflow.com/questions/38736048
复制相似问题