【发布时间】:2019-04-12 14:53:29
【问题描述】:
我想构建一个扫描本地蓝牙设备的应用。该应用程序会找到所有已配对的设备,但不会找到未配对的设备。我有一个按钮,当我按下它时,我想在Log 找到的设备中查看。
在AndroidManifest 中,我添加了BLUETOOTH、BLUETOOTH_ADMIN 和ACCESS_COARSE_LOCATION 的权限。
onCreate我得到了默认的蓝牙适配器并得到了配对的设备。
protected void onCreate(Bundle savedInstanceState) {
....
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(!bluetoothAdapter.isEnabled()) {
Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enable, REQUEST_ENABLE_BT);
}
pairedDevices = bluetoothAdapter.getBondedDevices();
///Add paired Devices
for(BluetoothDevice device : pairedDevices){
Log.i("DEVICE", device.getAddress()+" "+device.getName());
devicesList.add(device);
}
}
在onClick,我执行scanDevices 函数,我使用ScanCallBack。
final ScanCallback scanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
if(!devicesList.contains(result.getDevice())) {
Log.i("DEVICE", result.getDevice().getName()+ " "+result.getDevice().getAddress());
devicesList.add(result.getDevice());
}
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
}
};
bluetoothAdapter.getBluetoothLeScanner().startScan(scanCallback);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
bluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
}
}, 10000);
}
当我启动应用程序时,它什么也不做,日志中没有打印任何设备,当我尝试调试它时,它甚至不会在 ScanCallBack 中停止。
【问题讨论】:
-
你知道为什么第一次扫描没有找到所有设备吗?
标签: android bluetooth android-bluetooth