0

心拍計の心拍数を解析したい。そのために、最後に使用したデバイスを保存して、見つかったデバイスと比較したいと考えています。デバイスの検索には時間がかかるため、mDevice は null のままです。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());

}

googleマニュアルから引用:

    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 に答える