我正在开发一个基于传感器的应用程序,我通过BLE连接不断地收集传感器的数据,并将其显示在图形上。我想添加到应用程序的算法,将运行在每个新值收到,并显示在UI中的结果。由于数据传输是连续进行的,我希望算法将在后台运行,这样数据到图形的速度将保持不变。我正在阅读几种方法(AsyncTask、线程等)。但是作为一个新手: 1.我不能完全理解哪个更好2.我不能正确地实现它。
下面是相关的代码片段:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
//Call to the algorithm class
RespAlgo myAlgo = new RespAlgo();
@Override
protected void onCreate(Bundle savedInstanceState) {
//Code to initiate the graphs...
}
private final BluetoothGattCallback mGattCallback =
new BluetoothGattCallback() {
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)
{
// Here I catch the data from the BLE device
for (int i_bt_nTs = 0; i_bt_nTs < getResources().getInteger(R.integer.bt_nTs); i_bt_nTs++) {
//V2V8, S1, S2, S3
// k = R3/(Rs + R4) = V2V8/(ADCval * LSB / Gain + V2V8/2) - 1
// Rs = R3/k - R4
v2v8_val = v2v8_2_bval * 2 * adc_lsb * vbat_correction;
k = v2v8_val / (characteristic.getIntValue(FORMAT_UINT16, 2 + 6 * i_bt_nTs) * adc_lsb / ina_gain + v2v8_val / 2) - 1;
rs1 = R3 / k - R4;
//run the algorithm. the below should move to parallel task
// Add counter to the algorithm
myAlgo.addTime();
//Add value from the sensor to the algorithm
myAlgo.setValue(rs1);
//Return result to rr1 variable
rr1 = (float)myAlgo.getRR();
// Change the UI with the new value
myRR1.setText(String.valueOf(rr1));
}
}
发布于 2017-02-11 14:35:00
创建本地服务,并将传感器数据接收代码绑定到此本地服务。绑定后,您可以将消息发送到服务,让它在后台处理它,并更新UI或其他任何东西。你可以在这里阅读更多关于服务的信息- https://developer.android.com/guide/components/bound-services.html
另一个新的构造是使用事件总线,它将使您的代码完全解耦,并消除许多负担(如果您是Android新手,会发现这更容易)。点击此处- https://code.tutsplus.com/tutorials/quick-tip-how-to-use-the-eventbus-library--cms-22694
https://stackoverflow.com/questions/42176853
复制