【问题标题】:Start a background task when value changed java值更改时启动后台任务java
【发布时间】:2017-02-11 14:12:01
【问题描述】:

我正在开发一个基于传感器的应用程序,我通过 BLE 连接连续收集传感器的数据并将其显示在图表上。我想向应用程序添加一个算法,该算法将在收到的每个新值上运行并在 UI 中显示结果。由于数据传输是连续进行的,我希望算法将在后台运行,以便图形数据将保持速度。 我正在阅读几种方法(AsyncTask、Thread 等),但作为新手: 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));

        }
        }

【问题讨论】:

  • 很可能,AsyncTask 是最好的解决方案。它为并发提供了比 Thread 更高级别的抽象。
  • AsyncTask 可能是个问题,因为它基于固定大小的线程池,当大量任务排队等待执行时会导致问题。
  • 如果您认为您的活动可能会停止或更改,请使用服务并向活动报告。
  • @Linxy,停止或改变是什么意思?
  • 当您的算法正在运行时,用户可能会离开它,打开另一个活动或关闭应用程序。

标签: java android background-task


【解决方案1】:

创建一个本地服务,让您的传感器数据接收代码绑定到这个本地服务。绑定后,您可以向服务发送消息并让它在后台处理它并更新 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

【讨论】:

  • 谢谢,我会检查 Service 和 Eventbus。