无法在Android中检测到BLE Beacon

时间:2017-12-22 21:56:44

标签: android bluetooth-lowenergy

我正在尝试检测的信标在nRFConnect中显示为OK,如图nRFConnect所示。

但是,使用BLUETOOTH,BLUETOOTH_ADMIN和ACCESS_COARSE_LOCATION权限的我的安卓检测器代码在onScanResult ScanCallBack中从未说过“有一个!”,正如我所料。

你能发现我的问题吗?

谢谢!

public class MainActivity extends AppCompatActivity {

private BluetoothLeScanner mBluetoothLeScanner;
private BluetoothAdapter mBluetoothAdapter;
private ScanFilter mScanFilter;
private ScanSettings mScanSettings;
private TextView txtHello;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

    setScanSettings();
    setScanFilter();

    txtHello=findViewById(R.id.hello);
    mBluetoothLeScanner.startScan(Arrays.asList(mScanFilter), mScanSettings, mScanCallback);
}

public static byte[] getIdAsByte(java.util.UUID uuid)
{
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return bb.array();
}

protected ScanCallback mScanCallback = new ScanCallback() {

    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        txtHello.setText("Got one!");
        ScanRecord mScanRecord = result.getScanRecord();
        byte[] manufacturerData = mScanRecord.getManufacturerSpecificData(224);
        int mRssi = result.getRssi();
    }
};

private void setScanSettings() {
    ScanSettings.Builder mBuilder = new ScanSettings.Builder();
    mBuilder.setReportDelay(0);
    mBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER);
    mScanSettings = mBuilder.build();
}

private void setScanFilter() {
    ScanFilter.Builder mBuilder = new ScanFilter.Builder();
    ByteBuffer mManufacturerData = ByteBuffer.allocate(23);
    ByteBuffer mManufacturerDataMask = ByteBuffer.allocate(24);
    byte[] uuid = getIdAsByte(UUID.fromString("0CF052C2-97CA-407C-84F8-B62AAC4E9020"));
    mManufacturerData.put(0, (byte) 0xBE);
    mManufacturerData.put(1, (byte) 0xAC);
    for (int i=2; i<=17; i++) {
        mManufacturerData.put(i, uuid[i-2]);
    }
    for (int i=0; i<=17; i++) {
        mManufacturerDataMask.put((byte)0x01);
    }
    mBuilder.setManufacturerData(224, mManufacturerData.array(), mManufacturerDataMask.array());
    mScanFilter = mBuilder.build();
}

}

0 个答案:

没有答案