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

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...