每秒在后台检查 Room DB table 并显示通知

Checking Room DB table every seconds in Background and display Notification

我正在构建一个调度应用程序,我将所有调度的通知存储在房间数据库 Table 中,我想每秒检查一次当前 time/date 是否等于数据库 Table time/date,它应该显示通知。

我该怎么做?

在此处查看此 SO 问题:Repeat a task with a time delay? 查看 Handler's postDelayed 功能。从要检查的数据库中获取值,然后使用 postDelayed 检查它是否匹配

我认为你应该使用另一种设计模式来实现它而不是 "check every second",但这里有一个它如何工作的小片段:

final LiveData<Integer> id = scheduledRepository.getScheduledItemId(System.currentTimeMillis());
        id.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer integer) {
                if(integer == null){
                    //do nothing
                } else {
                    Toast.makeText(getApplicationContext(), YOUR_NOTIFICATION_TEXT, Toast.LENGTH_LONG).show();
                    id.removeObserver(this);
                    return;
                }
            }
        });

你的 DAO 将是这样的:

@Query("SELECT id FROM T_SCHEDULER WHERE date = :currentdate")
 LiveData<Integer> getScheduledItemId(long currentdate);

尝试这样的事情

Handler handler = new Handler();
int delay = 1000; //milliseconds

handler.postDelayed(new Runnable() {
    public void run() { //DB action here 
        //Todo, here you would put in your DB logic to check if the stuff matches
         handler.postDelayed(this, delay);
    }
}, delay);