安卓蓝牙LE扫描仪仅在某些设备中打开手机位置时进行扫描



我正在构建一个Android应用程序,该应用程序可以广告小信息包,并使用BLE扫描信息。广告代码为:

AdvertiseSettings advSettings = new AdvertiseSettings.Builder()
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
.setConnectable(false)
.build();

AdvertiseData advData = new AdvertiseData.Builder()
.setIncludeTxPowerLevel(true)
.addServiceUuid(uuid)
.build();
AdvertiseData advScanResponse = new AdvertiseData.Builder()
.setIncludeDeviceName(false)
.addServiceData(uuid,"1234567890".getBytes( Charset.forName( "UTF-8" ) ))
.build();
AdvertiseCallback advCallback = new AdvertiseCallback() {
String TAG="status";
@Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
Log.e(TAG, "Not broadcasting: " + errorCode);
int statusText;
switch (errorCode) {
case ADVERTISE_FAILED_ALREADY_STARTED:
Log.w(TAG, "ADVERTISE_FAILED_ALREADY_STARTED");
break;
case ADVERTISE_FAILED_DATA_TOO_LARGE:
Log.w(TAG, "ADVERTISE_FAILED_DATA_TOO_LARGE");
break;
case ADVERTISE_FAILED_FEATURE_UNSUPPORTED:
Log.w(TAG, "ADVERTISE_FAILED_FEATURE_UNSUPPORTED");
break;
case ADVERTISE_FAILED_INTERNAL_ERROR:
Log.w(TAG, "ADVERTISE_FAILED_INTERNAL_ERROR");
break;
case ADVERTISE_FAILED_TOO_MANY_ADVERTISERS:
Log.w(TAG, "ADVERTISE_FAILED_TOO_MANY_ADVERTISERS");
break;
default:
Log.wtf(TAG, "Unhandled error: " + errorCode);
}
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
Log.v(TAG, "Advertising started");
mText.setText(uuid.toString());
Toast.makeText(MainActivity.this, "Started", Toast.LENGTH_SHORT).show();
}
};
mBluetoothAdapter.getBluetoothLeAdvertiser()
.startAdvertising(advSettings, advData, advScanResponse, advCallback);

监听的代码如下:

mBluetoothLeScanner=mBluetoothAdapter.getBluetoothLeScanner();

ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
if( result == null
|| result.getDevice() == null
)
return;
if(result.getScanRecord().getServiceUuids()!=null) {
ParcelUuid pp=result.getScanRecord().getServiceUuids().get(0);
StringBuilder builder = new StringBuilder((pp.toString()+"n"));
builder.append(new String (result.getScanRecord().getServiceUuids().size()+""));
mText.setText(builder.toString());
}

我在多部手机上测试过,效果很好。然而,Galaxy S8+上的Android 9.0版本无法扫描,除非打开位置。我也在Redmi Note 7上尝试了Android 9.0版本,它无需打开位置即可完美工作。是什么导致了我的问题?

不确定Redmi Note 7上的安卓设置,但对于安卓9设备,需要打开ACCESS_COARSE_LOCATION才能使用蓝牙。也许这在Redmi Note 7上是以某种方式打开的,而不管位置设置如何,而在S8+上,这与位置设置有关。

你可以在这里找到更多信息:-

https://stackoverflow.com/a/58232014/2215147

我希望这能有所帮助。

相关内容

  • 没有找到相关文章