每天在特定时间向房间数据库添加一个项目

Adding an item to Room Database at specific time every day

我需要每天凌晨 12 点将项目添加到 Room Database 的代码。我尝试了很多方法,例如 WorkManagerAlarmManager 但他们没有达到这个目标

这是我在评论中提到的内容的实现:

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 到 post 任务。

您可以将代码移动到任何您想要的地方,很可能是在您的存储库或视图模型中(如果有的话)。对于计时器,您可以将 RxJava 用于应用内计时器或其他任何东西。

如果用户将时间更改为早几天,添加的项目将不会被删除。如果用户随后将其设置回正常状态,某些天的项目将被复制。如果时间大于上次保存的时间,您可以通过仅在 onPause 中保存时间来防止这种情况。