0

我想分析心率监测器的心率。为此,我想保存最后使用的设备并将其与找到的设备进行比较。因为查找设备需要一段时间,所以 mDevice 保持为空。我该怎么做才能正确更新 mDevice?

private ArrayList<BluetoothDevice> mDeviceList;
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
private BluetoothDevice mDevice;

private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;

    @Override
protected void onStart() {
    super.onStart();
    // Ensures Bluetooth is enabled on the device.  If Bluetooth is not currently enabled,
    // fire an intent to display a dialog asking the user to grant permission to enable it.
    if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }


    // Initializes list view adapter.
    mDeviceList = new ArrayList<BluetoothDevice>();
    scanLeDevice(true);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final String adress = prefs.getString(getString(R.string.device_address), "");

    for(BluetoothDevice b : mDeviceList){
        if(b.getAddress().equals(adress)){
            mDevice = b;
        }
    }
    if(mDevice != null)
        Log.e(TAG, mDevice.getAddress());

}

取自谷歌手册:

    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);
                invalidateOptionsMenu();
            }
        }, SCAN_PERIOD);
        mScanning = true;
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    } else {
        mScanning = false;
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }
    invalidateOptionsMenu();
}

// Device scan callback.
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() {
                        if(!mDeviceList.contains(device)){
                            mDeviceList.add(device);
                        }
                    }
                });
            }
        };

我希望这些是足够的信息。如果缺少什么,请随时询问

4

2 回答 2

0

只需将您的代码移动到您尝试查找最后一个设备的位置(onStart()之后的所有内容SharedPreferences prefs...),然后移动到您已经找到设备之后,例如在您的可运行文件结束时(之后invalidateOptionsMenu();

于 2014-05-28T13:23:40.960 回答
0

扫描是一项后台活动,您尝试在启动后立即查看结果,而不是等待它完成。您可能希望将检查代码直接放入 onLeScan 回调中,并在看到所需设备后立​​即停止扫描。

如果您已经拥有设备的详细信息,您也可以尝试不一起进行扫描,直接尝试连接。文档中根本不清楚是否需要在连接之前进行扫描的详细信息,因此您需要准备好进行一些实验,因为它仍然太不稳定了。

于 2014-05-26T12:25:23.510 回答