Android:从给定时间开始计算天数,而不依赖操作系统时间



在我的应用程序中,如果用户 30 天没有刷新对象,我需要更新它。我尝试了几种方法来解决这个问题,但没有一件奏效

1. 使用System.currentTimeMillies()

我的第一次尝试是只存储对象更新的时间并将其与当前时间进行比较。一切正常,但问题是,用户可以更改操作系统时间,然后时间检查将毫无用处......

2. 使用AlarmManager

在这里我遇到了与上面相同的问题

3. 实现包含计时器的服务

在这里,我实现了一个带有计时器的Service,该计时器最多只能计算 30 天。这似乎是最好的解决方案,但是当我关闭应用程序时,服务停止。 我的服务的onCreateonStartCommand如下所示(我只是将 30 天更改为 2 分钟进行测试,它包含多个对象的多个计时器(:

@Override
public void onCreate() {
Log.i(TAG, "[onCreate]");
super.onCreate();
registerReceiver(new StopServiceReceiver(), new IntentFilter(STOP_SERVICE_REQUEST));
context = this;
//retrieveTimers();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) {
Log.i(TAG, "[onStartCommand] intent = null");
return super.onStartCommand(intent, flags, startId);
}
//prevent starting 2 timers for the same id
String id = intent.getStringExtra(KEY_CARD_ID);
if (timerHashMap.containsKey(id)) {
Log.i(TAG, "[onStartCommand] timer already exists");
return super.onStartCommand(intent, flags, startId);
}
//create and start timer
Log.i(TAG, "[onStartCommand] schedule timer");
Timer timer = new Timer();
timer.schedule(new CounterTask(id), MAX_MILLIES_WITHOUT_UPDATE);
timerHashMap.put(id, timer);
// storeTimers();
return super.onStartCommand(intent, flags, startId);
}

我还尝试将计时器映射存储在共享首选项中,但后来我意识到这有点愚蠢,因为计时器应该继续并且序列化计时器来存储它也是不可能的(正如我所说有点愚蠢;-((

感谢您的帮助!

您可以使用JobScheduler(或它的某些变体(。

Minimum LatencyPeriodic选项可用于计划作业在 30 天后运行。

有关详细信息,请参阅本文:使用 JobScheduler 像专业人士一样计划作业

最新的支持库中有JobIntentService和Firebase JobDispatcher,以实现向后兼容性。

最新更新