我想分析心率监测器的心率。为此,我想保存上次使用的设备并将其与找到的设备进行比较。由于查找设备需要一段时间,因此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);
}
}
});
}
};
我希望这些是足够的信息。如果缺少某些东西,请随时询问
答案 0 :(得分:0)
扫描是一种后台活动,您尝试在启动后直接查看结果,而不是等待它完成。您可能希望直接将检查代码放入onLeScan回叫中,并在看到所需设备后立即停止扫描。
如果您已经拥有设备的详细信息,请尝试直接连接,您也可以尝试不一起扫描。在连接之前需要扫描的细节在文档中并不清楚,因此您需要准备好进行一些实验,因为它仍然太过于片状。
答案 1 :(得分:0)
在您找到设备之后,只需将代码移动到您尝试查找最后一个设备(onStart()
之后SharedPreferences prefs
中的所有内容...)之后,例如在您的runnable结束时(在invalidateOptionsMenu();
)之后