如何在JobIntentService中读取传感器?

时间:2018-02-19 16:24:14

标签: android android-4.4-kitkat android-sensors android-8.0-oreo jobintentservice

我正在从API级别19开始编写针对8 Oreo的Android应用。我想查询Sensor.TYPE_STEP_COUNTER的数据。由于我的理解没有办法直接读取当前值,我必须创建一个SensorEventListener等待onSensorChanged(SensorEvent event)。如何在JobIntentService中正确执行此操作? 由于onHandleWork(@NonNull Intent intent)意味着完成工作然后完成,我目前的解决方案是阻止线程:

/// we need to wait for the sensor to return it's data in onSensorChanged
while (isWaitingForSensor) {
    /// block the thread to not end the Job
    try {
        Thread.sleep(SLEEP_TIME_MS);
        waitTime += SLEEP_TIME_MS;
        if (waitTime >= MAX_WAIT_TIME) {
            isWaitingForSensor = false;
        }
    } catch (InterruptedException e) {
    }
}

以及我的SensorEventListener

public void onSensorChanged(SensorEvent event) {
    int stepCount = event.values[0];
    ...
    isWaitingForSensor = false;
}

有人有更好的解决方案吗?

0 个答案:

没有答案