0

I am building a scheduling App, I store all scheduled notification inside a Room DB Table, I want to check every second if the current time/date is equal to the DB Table time/date, and it's should display a notification for it.

How can I do this?

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
SilenceCodder
  • 2,874
  • 24
  • 28

3 Answers3

1

Have a look at this SO question here : Repeat a task with a time delay? have a look at Handler's postDelayed feature. get the value from the database you want to check and then use a postDelayed to check if it matches up

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
1

I think you should use another design pattern to implement it instead of "check every second", but here is a little snippet how it could work:

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

Your DAO will be something like this:

@Query("SELECT id FROM T_SCHEDULER WHERE date = :currentdate")
 LiveData<Integer> getScheduledItemId(long currentdate);
Levente Takács
  • 435
  • 4
  • 15
  • Will I implement this inside a button or what?, because I think the code should be inside a service or background? – SilenceCodder Jul 17 '19 at 09:08
  • try to put it in a handler like this: `Handler handler = new Handler(); int delay = 1000; //milliseconds handler.postDelayed(new Runnable(){ public void run(){ //DB action here handler.postDelayed(this, delay); } }, delay);` – Levente Takács Jul 17 '19 at 09:16
0

Try something like this

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);
a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
  • Am really busy with something else, I just implement it yesterday and it works, but sometimes it works when I minimize the app and also close the entire app. what can I do to achieve this. And also how can I pause it and let it continue when it performed something. – SilenceCodder Jul 22 '19 at 08:43
  • you would have to look into creating a service for something like that @Harbdollar – a_local_nobody Jul 22 '19 at 10:02
  • Yea, I know about service, That means I have to add it inside a service, – SilenceCodder Jul 24 '19 at 07:18