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

时间:2019-07-17 08:14:17

标签: android notifications background schedule

我正在构建一个调度应用程序,我将所有调度的通知存储在Room DB表中,我想每秒检查一次当前时间/日期是否等于DB Table的时间/日期,并且应该显示一个通知它。

我该怎么做?

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

我认为您应该使用另一种设计模式来实现它,而不是“每秒检查一次”,但这是一个小片段,它是如何工作的:

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);

答案 2 :(得分:0)

尝试类似的方法

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);
相关问题