我正在尝试通过 BLE 编写一个聊天应用程序 android 应用程序.
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
我在 log cat 中收到了该消息,并且在扫描设备时没有触发 onLeScan()
方法。
D/BluetoothAdapter: startLeScan(): null
D/BluetoothAdapter:onClientRegistered() - status=0 clientIf=5
D/BluetoothAdapter: stopLeScan()
我的扫描设备代码是
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, device.getName(), Toast.LENGTH_SHORT)
.show();
}
});
}
};
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
当我检查我的设备规范时,它们只支持蓝牙智能,不支持外设模式。我的问题是,是否可以在不支持外设模式的情况下将支持 BLE 的手机相互连接?还是我的代码有问题?
编辑
我有 3 台测试设备,分别是 Android 4.3 的华为 730、Android 4.4.2 的三星 galaxy core 2 和 Android 6.0.1 的 Android 设备。他们都遇到了我的问题。我还测试了 BLEScanner但没有检测到我所有的设备。此外,我无法通过运行来自 android sdk 的示例项目 BluetoothLeGatt 来检测我的所有设备。
最佳答案
我找到了答案。这是因为 Lollipop 之前的设备不支持外设模式。作为外围设备的您的一部手机必须具有 android 5.0 (Lollipop) 及更高版本,以便它可以宣传其存在,创建 GATTServer 并让另一部手机作为中心/客户端连接它。
Make communication between 2 android phones over BLE
https://developer.android.com/about/versions/android-5.0.html#BluetoothBroadcasting
编辑
甚至部分 Lollipop 及以上手机由于硬件要求不支持外设模式。
希望对你有用。
关于android - 扫描设备失败android BLE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35069988/