我正在开发带有蓝牙的 Android 应用程序,但有时我在发现 LE 设备时遇到问题:通常发现回调会返回找到的设备,但有时会停止工作并且不返回设备。
我在不同的设备(三星、LG)和不同的 Android 版本(8.0、6.0、4.4)上测试了代码(在调试模式下),但问题是一样的,不是系统的,一段时间后,它恢复正常。
我已经应用了在互联网上找到的所有建议:
但问题仍然存在。
下面是清单的片段:
.
.
.
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
.
.
.
和蓝牙代码:
public BLEH_RES StartDiscovery()
{
.
.
.
CheckPermission();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
return(scanLeDevice21(true));
else
return(scanLeDevice18(true));
}
/**
* Scan BLE devices on Android API 20 to last version (Android 9.0)
*
* @param enable Enable scan
*/
@RequiresApi(21)
private BLEH_RES scanLeDevice21(boolean enable)
{
bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
if (bluetoothLeScanner == null)
return(BLEH_RES.BLE_NOT_SUPPORTED);
if (enable)
{
ScanSettings.Builder scanSettings = new ScanSettings.Builder();
scanSettings.setScanMode(SCAN_MODE_LOW_LATENCY);
bluetoothLeScanner.startScan(null, scanSettings.build(), BLEScanCallback);
}
else
bluetoothLeScanner.stopScan(BLEScanCallback);
return(BLEH_RES.OK);
}
/**
* Scan BLE devices on Android API 18 to 20
*
* @param enable Enable scan
*/
private BLEH_RES scanLeDevice18(boolean enable)
{
if(bluetoothAdapter == null)
return(BLEH_RES.BT_NOT_SUPPORTED);
if (enable)
{
bluetoothAdapter.startDiscovery();
bluetoothAdapter.startLeScan(mLeScanCallback);
}
else
{
bluetoothAdapter.cancelDiscovery();
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
return(BLEH_RES.OK);
}
@RequiresApi(21)
private ScanCallback BLEScanCallback = new ScanCallback()
{
@Override
public void onScanResult(int callbackType, ScanResult result)
{
addDevice(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
}
@Override
public void onScanFailed(int errorCode)
{
for(ErrorEvent ee:errorEventList)
ee.onError(BLEH_EVENT_ERROR.SCAN_FAILED);
}
};
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback()
{
@Override
public void onLeScan(final BluetoothDevice bluetoothDevice, int rssi,byte[] scanRecord)
{
addDevice(bluetoothDevice, rssi, scanRecord);
}
};
你能建议我解决这个问题吗?
我按照此链接中的建议解决了我的问题:https : //stackoverflow.com/a/42267678/7006955
我将所有建议的代码添加到我的代码中,它在 Android 4 中也能正常工作
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句