如何让计时器在后台运行以在特定时间段后执行操作?



我有一个按钮,每天限制 5 个,每月限制 30 个。每次单击它时,它都会从每日剩余和每月剩余中减少 1。点击 5 次后,每天剩余点击为 0,每月剩余为 25。如何在后台每 24 小时将此计数器重置为 5,即使应用程序未运行或设备未打开。以及我如何在 30 天(月(后做同样的事情。目前,我正在使用共享首选项在需要时更新值。但我希望这种情况定期发生,而不是每次启动应用程序时

sharedPreferences.edit().putInt("dailyRemaining", dailyRemaining).apply(); //5
sharedPreferences.edit().putInt("monthlyRemaining", monthlyRemaining).apply(); //30

要在一定时期后执行任何任务,您必须参考 android 工作管理器或 android 作业。

工作管理器 [ https://developer.android.com/topic/libraries/architecture/workmanager ]

印象笔记安卓工作 [ https://github.com/evernote/android-job ]

希望对您有所帮助。

这是一个相对简单的任务,可以在后台完成,而当应用程序启动时可以简单地完成。实现和维护后台任务本身就是一项艰巨的工作,因此,如果您在更改日期时不需要在后台执行任何操作(例如发送通知或将该信息发送到后端等(,我建议保持简单并在 UI 级别。

你可以在主Activity中做这样的事情,或者覆盖你的Application类,在那里做(:

// Build today date and current month strings which will be used as keys
String todayDate = getDateFromFormat("dd-MM-yyyy");
String currentMonth = getDateFromFormat("MM-yyyy");
// Try to get the remaining limit from sharedpreferences, and give them default
// values if they don't exist yet
int remainingForToday = sharedPreferences.getInt(todayDate, 5);
int remainingThisMonth = sharedPreferences.getInt(currentMonth, 30);
// When the user clicks on the button, decrement and save the remaining 
sharedPreferences.edit().putInt(todayDate, remainingForToday - 1).apply();
sharedPreferences.edit().putInt(currentMonth, remainingThisMonth - 1).apply();
// Utility function to get the date time strings using native Java classes
private String getDateFromFormat(String format) {
Calendar today = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(today.getTime());
}

上面所做的是将今天的日期和当前月份key,该月份对于每天和每个月都是唯一的。只需在此基础上检查您的剩余限制即可。

为了每24小时重置一次值,您可以使用AlarmManager。有了它,您可以安排服务的执行,该服务将在SharedPreferences中重置值。但是AlarmManager有问题,一旦手机重新启动,您必须重新安排它。不用担心,这里是解释如何处理所有这些事情的指南。

您也可以使用新的工作管理器API。 + 手码实验室如何使用它

最新更新