仅在按下按钮时检测低能量蓝牙设备

时间:2016-03-14 06:27:39

标签: android bluetooth bluetooth-lowenergy android-bluetooth android-ibeacon

我正在尝试使用低能量蓝牙信标构建应用程序,对于Android,只要信标靠近我的手机,它就会在没有按下按钮的情况下被检测到

我想要的是只有在按下信标按钮时才能检测到

我正在使用的代码是

 private void scanLeDevice(final boolean enable) {
    if (enable) {

        if (Build.VERSION.SDK_INT < 21) {
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mLEScanner.startScan(filters, settings, mScanCallback);
        }
    } else {
        if (Build.VERSION.SDK_INT < 21) {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        } else {
            mLEScanner.stopScan(mScanCallback);
        }
    }
}

private ScanCallback mScanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        Log.i("callbackType", String.valueOf(callbackType));
        Log.i("result", result.toString());
        BluetoothDevice btDevice = result.getDevice();
        connectToDevice(btDevice);
    }

    @Override
    public void onBatchScanResults(List<ScanResult> results) {
        for (ScanResult sr : results) {
            Log.i("ScanResult - Results", sr.toString());
        }
    }

    @Override
    public void onScanFailed(int errorCode) {
        Log.e("Scan Failed", "Error Code: " + errorCode);
    }
};

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() {
                        Log.i("onLeScan", device.toString());
                        connectToDevice(device);
                    }
                });
            }
        };

public void connectToDevice(BluetoothDevice device) {

}

我是否需要实现任何gatt回调或是否有任何方法,以便在点击按钮时收到通知

1 个答案:

答案 0 :(得分:0)

试试这个:

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);
                cancelButton.setText(R.string.scan);
            }
        }, SCAN_PERIOD);

        mScanning = true;
        mBluetoothAdapter.startLeScan(mLeScanCallback);
        cancelButton.setText(R.string.cancel);
    } else {
        mScanning = false;
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        cancelButton.setText(R.string.scan);
    }

}