Как подсчитать время, прошедшее между выходом из приложения и входом?
В методе onStop перед выходом я сохраняю текущее время в секундах, так же я сохраняю время, прошедшее от запуска до выключения приложения
@Override
protected void onStop() {
SharedPreferences.Editor editor = mSettings.edit();
int day = calendar.get(Calendar.DAY_OF_YEAR);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int seconds = day * 86400 + hour * 3600 + minute * 60 + second;
editor.putInt("lastSeconds", seconds);
editor.putInt("seconds", seconds);
editor.putInt("minutes", minutes);
editor.putInt("hours", hours);
editor.putInt("days", days);
editor.apply();
super.onStop();
}
Когда приложение запускается, в методе onCreate я вычитаю разницу между текущим временем в секундах и временем, сохраненным перед закрытием приложения. Затем, ко времени, которое я провел в приложении я добавляю эту разницу. Но в итоге получается черти что, даже отрицательные значения бывают.
longSeconds = calendar.get(Calendar.DAY_OF_YEAR) * 86400 + calendar.get(Calendar.HOUR) * 3600 + calendar.get(Calendar.MINUTE) * 60 + calendar.get(Calendar.SECOND);
int difSec = longSeconds - mSettings.getInt("lastSeconds", longSeconds);
days = mSettings.getInt("days", 0) + (int)Math.floor(difSec/86400);
difSec -= days*86400;
hours = mSettings.getInt("hours", 0) + (int)Math.floor(difSec/3600);
difSec -= hours*3600;
minutes = mSettings.getInt("minutes", 0) + (int)Math.floor(difSec/60);
difSec -= minutes*60;
seconds = mSettings.getInt("seconds", 0) + difSec;
Подскажите, что мне делать? Как правильно вычитать время между текущим и прошедшим с момента закрытия приложения?
Ответы (1 шт):
editor.putInt("seconds", seconds); // <- s в конце лишняя
нужно
editor.putInt("seconds", second);
Если ключ назвается lastSeconds, то логично и переменную для этого ключа назвать lastSeconds. Тогда для ключа seconds можно использовать seconds, а не second, чтобы не было путаницы.