我需要在每天的12 AM将代码添加到RecyclerView
的代码。我已经尝试了许多方法,例如工作管理器和警报管理器,但是它们没有实现此目标
这里是我在评论中提到的实现:
public class MainActivity extends AppCompatActivity {
private static final String PREF_PAUSE_TIME_KEY = "exit_time";
private static final Long MILLIS_IN_DAY = 86400000L;
private static final int TRIGGER_HOUR = 12;
private static final int TRIGGER_MIN = 0;
private static final int TRIGGER_SEC = 0;
private final Handler handler = new Handler();
private SharedPreferences prefs;
private final Calendar calendar = Calendar.getInstance();
private final Runnable addItemRunnable = new Runnable() {
@Override
public void run() {
handler.postDelayed(addItemRunnable, MILLIS_IN_DAY);
addItem();
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
@Override
protected void onResume() {
super.onResume();
// Add missing events since onPause.
long resumeTime = System.currentTimeMillis();
long pauseTime = prefs.getLong(PREF_PAUSE_TIME_KEY, resumeTime);
// Set calendar to trigger time on the day the app was paused.
calendar.setTimeInMillis(pauseTime);
calendar.set(Calendar.HOUR_OF_DAY, TRIGGER_HOUR);
calendar.set(Calendar.MINUTE, TRIGGER_MIN);
calendar.set(Calendar.SECOND, TRIGGER_SEC);
long time;
while (true) {
// If calendar time is during the time that app was on pause, add item.
time = calendar.getTimeInMillis();
if (time > resumeTime) {
// Past current time, all items were added.
break;
} else if (time >= pauseTime) {
// This time happened when app was on pause, add item.
addItem();
}
// Set calendar time to same hour on next day.
calendar.add(Calendar.DATE, 1);
}
// Set handler to add item on trigger time.
handler.postDelayed(addItemRunnable, time - resumeTime);
}
@Override
protected void onPause() {
super.onPause();
// Save pause time so items can be added on resume.
prefs.edit().putLong(PREF_PAUSE_TIME_KEY, System.currentTimeMillis()).apply();
// Cancel handler callback to add item.
handler.removeCallbacks(addItemRunnable);
}
private void addItem() {
// Add item to database and RecyclerView.
}
}
onPause
时,当前时间保存在首选项中。onResume
时,程序将添加应在未打开应用程序时添加的所有项目。Handler
在特定时间发布任务。您可以将代码移动到所需的任何位置,如果有的话,很可能将其移动到存储库中或查看模型中。对于计时器,您可以将RxJava用于应用内计时器或其他任何计时器。
如果用户将时间更改为几天前,添加的项目将不会被删除。如果用户随后将其设置为正常,几天后的项目将被复制。您可以通过仅在onPause
中保存比上次保存的时间长的时间来防止这种情况。