Notifications in specific time every day android

前端 未结 2 2014
逝去的感伤
逝去的感伤 2020-12-02 19:46

I\'d like to make an app that let the user decide what time everyday wants him to remind something with notification...

I\'d like to know how am i supposed to trigge

相关标签:
2条回答
  • 2020-12-02 20:12

    I know this is an old question but I had a similar requirement and this is what I did. I found the difference between the current system time and the intended time for sending notification in millis and implemented a runnable inside an android service. The below code will come in the Notifyservice.

    private Handler notificationTimer = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==0) {
                    sendNotifications();
            }
            super.handleMessage(msg);
        }
    };
    private Runnable notificationCaller = new Runnable() {
    
        @Override
        public void run() {
            Message msg = notificationTimer.obtainMessage();
            msg.what = 0;
            notificationTimer.sendMessage(msg);
        }
    };        
    
    
        Calendar calendar = Calendar.getInstance();
        Calendar timefornotification = Calendar.getInstance();
        timefornotification.set(Calendar.HOUR_OF_DAY, 12);
        timefornotification.set(Calendar.MINUTE, 30);
        timefornotification.set(Calendar.SECOND, 00);
    
        Long difference = calendar.getTimeInMillis() - timefornotification.getTimeInMillis();
    
        if(difference<0){
            notificationTimer.postDelayed(notificationCaller, -(difference));
        }
        else{
            notificationTimer.postDelayed(notificationCaller, difference);
        }
    
       public void sendNotifications(){
            ------Your code here-------
            notificationTimer.removeCallbacksAndMessages(null);
            notificationTimer.postDelayed(notificationCaller, 86400000);
            ------86400000 is one day. So it will repeat everyday-------
       }
    

    You can then call a service from main class to run this in background.

       Intent service = new Intent(this, NotifyService.class);
        this.startService(service);
    
    0 讨论(0)
  • 2020-12-02 20:20

    Use alarm manager and put your notification in NotifyService class

    Intent myIntent = new Intent(Current.this , NotifyService.class);     
    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    pendingIntent = PendingIntent.getService(ThisApp.this, 0, myIntent, 0);
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 12);
    calendar.set(Calendar.MINUTE, 00);
    calendar.set(Calendar.SECOND, 00);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY , pendingIntent);  //set repeating every 24 hours
    
    0 讨论(0)
提交回复
热议问题