我正在编写一个类似于计步器的Android应用程序。我已经为每日半夜清洁脚步的功能苦苦挣扎了很长一段时间。我的功能无法正常工作,请帮助我。
听众:
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
SharedPreferences prefs = getSharedPreferences("stats", Context.MODE_PRIVATE);
float stepsAtMidnight = prefs.getFloat("steps", 0);
float stepsToday = event.values[0] - stepsAtMidnight;
if (stepsToday >= 0) {
dsteps.setText(String.valueOf((int) stepsToday));
dsteps1.setText(String.valueOf((int) stepsToday));
float kmm = (stepsToday * 75) / 100000;
km.setText(String.format("%.1f km", kmm));
kcal.setText((int)(stepsToday * 0.04) + " kcal");
}
}
}
警报:
public void setMidnightResetAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, StepCounterResetReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Moscow"));
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Toast.makeText(context, "Alarm set for midnight", Toast.LENGTH_SHORT).show();
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
接收者:
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Сброс шагов", Toast.LENGTH_SHORT).show();
SharedPreferences prefs = context.getSharedPreferences("stats", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
float lastSavedSteps = prefs.getFloat("laststeps", 0);
editor.putFloat("steps", lastSavedSteps);
editor.apply();
}