微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,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(),它认返回当前日期时间,并且您的通知将每天同时显示.如果要为警报指定不同的时间,请使用所需的时间传入日期对象!

编辑

确保代码只运行一次的简单方法是使用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);

原文地址:https://www.jb51.cc/android/430889.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐