我一直在尝试检索间隔为30秒的步骤数。我使用TYPE_STEP_COUNTER
传感器和一个实现SensorEventListener
接口的自定义类。我当前的实现如下所示:
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class StepSensor extends JobService implements SensorEventListener {
private static final String TAG = "StepSensor";
public static final Integer JOB_ID = TAG.hashCode();
private SensorManager sensorManager;
private Sensor stepSensor;
@Override
public boolean onStartJob(JobParameters params) {
logStepInformation();
return false;
}
private void logStepInformation() {
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
stepSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
sensorManager.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
public boolean onStopJob(JobParameters params) {
return false;
}
@Override
public void onSensorChanged(SensorEvent event) {
StringBuilder stringBuilder = new StringBuilder();
long milliseconds = TimeUnit.MILLISECONDS.convert(event.timestamp, TimeUnit.NANOSECONDS);
stringBuilder.append("Registered ");
stringBuilder.append(event.values[0]);
stringBuilder.append(" steps at ");
stringBuilder.append(new Date(milliseconds).toString());
System.out.println(stringBuilder.toString());
sensorManager.unregisterListener(this);
stopSelf();
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Nothing
}
}
该类将传递给JobScheduler
实例,并在后台运行:
JobScheduler jobSchedulerstepcounter =
(JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobSchedulerstepcounter.schedule(new JobInfo.Builder(StepSensor.JOB_ID,
new ComponentName(this, StepSensor.class))
.setPeriodic(ParamsLogging.STEPCOUNTER_CONTROL_INTERVAL_MILLIS)
.build());
其中
public static final long STEPCOUNTER_CONTROL_INTERVAL_MILLIS = 30*1000L;
但是,似乎SensorEvent
中存储的值已经过时,并且在此间隔内执行的步骤没有改变:
Registered 134.0 steps at Thu Jan 01 23:04:32 MEZ 1970
Registered 134.0 steps at Thu Jan 01 23:05:02 MEZ 1970
Registered 134.0 steps at Thu Jan 01 23:05:32 MEZ 1970
Registered 134.0 steps at Thu Jan 01 23:06:02 MEZ 1970
注意:该应用程序不拥有作为参数传递的事件对象,因此无法保留该对象。该对象可能是内部池的一部分,并且可以被框架重用。
我认为,作为参数传递的SensorEvent
对象始终与更新的时间戳相同。可以注册活动时获取的实际步骤数吗?
我使用的是Android 5.0.2版。