简体   繁体   English

如何在特定时间内自动启用/禁用推送通知

[英]How to automatic enable/disable push notification for certain time

I'm new at using an alarm service for Android.我是使用 Android 警报服务的新手。 I want to create a medication reminder which is the medication information and number of repeated notification per day as the input data.我想创建一个用药提醒,它是用药信息和每天重复通知的次数作为输入数据。 However, I only want to enable the notification between 7 AM and 7 PM.但是,我只想在早上 7 点到晚上 7 点之间启用通知。 So, the apps will notify within that time only and also the apps will start to notify at 7 AM.因此,应用程序将仅在该时间内通知,并且应用程序将在上午 7 点开始通知。

Example: If the user wants to repeat the notification from the apps 3 times per day, then every 4 hours the apps will notify them to take the medicine (12 hours / 3 times = 4 hours).示例:如果用户想每天重复 3 次应用程序的通知,则应用程序将每 4 小时通知他们吃药(12 小时 / 3 次 = 4 小时)。

I have tried using the while loop, however it somehow didn't worked as I expected where if the condition is true, then it will keep on notify even though it's not the time yet (this happened to my code).我试过使用 while 循环,但是它在某种程度上没有按我预期的那样工作,如果条件为真,那么它会继续通知,即使现在还不是时候(这发生在我的代码上)。

So, here what I tried to do:所以,在这里我试图做的是:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 7);
while(calendar.get(Calendar.HOUR_OF_DAY) >= 0) {
    while (calendar.get(Calendar.HOUR_OF_DAY) >= 7 && calendar.get(Calendar.HOUR_OF_DAY) <= 19) {
           // the process here
    }
    calendar.add(Calendar.HOUR_OF_DAY, 1);
}

I'm sorry if my code is lacking in many ways.如果我的代码在很多方面都缺乏,我很抱歉。 But, I really hope that you guys can help me or share with me any other possible solution.但是,我真的希望你们能帮助我或与我分享任何其他可能的解决方案。 Thank you.谢谢你。

You are setting the calendar hour incorrectly.您设置的日历时间不正确。

Replace代替

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 7);
while(calendar.get(Calendar.HOUR_OF_DAY) >= 0) {
    while (calendar.get(Calendar.HOUR_OF_DAY) >= 7 && calendar.get(Calendar.HOUR_OF_DAY) <= 19) {
           // the process here
    }
    calendar.add(Calendar.HOUR_OF_DAY, 1);
}

With

Calendar cc = Calendar.getInstance();
int mHour = cc.get(Calendar.HOUR_OF_DAY);

if (mHour  >= 7 && mHour  <= 19) {
               // the process here
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM