繁体   English   中英

PhoneGap Android中每天都会重复本地通知

[英]Local Notification repeated every day in PhoneGap Android

我正在尝试使用我在github上找到的LocalNotification插件每天从我的应用程序发送通知。 我有以下代码,一旦应用程序启动就会发送通知。

    var notification = cordova.require("cordova/plugin/localNotification");

              document.addEventListener('deviceready', onDeviceReady, false);

              function onDeviceReady() {
                alert('device ready');
               var id = 0;
      id++;
      newDate = new Date();
      newDate.setUTCHours(1,30,1);
          notification.add({
                id : id,
                date : newDate,
                message : "Your message here",
                subtitle: "Your subtitle here",
                ticker : "Ticker text here",
                repeatDaily : true
          });                
}

但我希望应用程序在不打开的情况下自动发送通知。 将选项repeatDaily设置为true会有帮助吗?

我做了我的研究,发现其他人能够使用LocalNotification插件实现它。

我不太确定如何测试,因为它要求我保持AVD开启一整天。 目标很简单。 我需要每天向用户发送一个通知,而无需打开应用程序。 任何帮助将受到高度赞赏! 谢谢 !!

我自己从未使用过这个插件,但是对代码进行一点挖掘就会向我显示,只要你将repeatDaily设置为true你的通知就会每天都在那里。

如果您查看AlarmHelper类,您可以看到该参数设置的if子句每天都重复。

final AlarmManager am = getAlarmManager();

...

if (repeatDaily) {
        am.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, AlarmManager.INTERVAL_DAY, sender);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, triggerTime, sender);
    }

AlarmReceiver类中解释的一个额外细节是,如果您设置上一次的时间(例如现在是11:00并且您将警报设置为每天在08:00重复),它将立即触发,然后在第二天预定的时间。 所以该类有一个if子句来防止这种情况发生。

if (currentHour != alarmHour && currentMin != alarmMin) {
            /*
             * If you set a repeating alarm at 11:00 in the morning and it
             * should trigger every morning at 08:00 o'clock, it will
             * immediately fire. E.g. Android tries to make up for the
             * 'forgotten' reminder for that day. Therefore we ignore the event
             * if Android tries to 'catch up'.
             */
            Log.d(LocalNotification.PLUGIN_NAME, "AlarmReceiver, ignoring alarm since it is due");
            return;
        }

要设置日期,请使用date参数。 在您的示例中,您使用的是new Date() ,它默认返回当前日期时间,并且您的通知将每天同时显示。 如果要为警报指定不同的时间,请使用所需的时间传入日期对象!

编辑

确保代码只运行一次的简单方法是使用localstorage。

function onDeviceReady(){
   ...
   //note that this will return true if there is anything stored on "isAlarmSet"
   var isSet = Boolean(window.localStorage.getItem("isAlarmSet")); 
   if (isSet){
       //Alarm is not set, so we set it here
       window.localStorage.setItem("isAlarmSet",1);
    }
}

如果您取消设置闹钟,请务必清除变量:

localStorage.removeItem("isAlarmSet);

暂无
暂无

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

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