在PhoneGap Android中每天重复本地通知
我每天都试图使用我在github找到的LocalNotification插件从我的应用程序发送通知。我有以下代码,它在应用程序启动时立即发送通知在PhoneGap Android中每天重复本地通知,android,cordova,phonegap-plugins,localnotification,Android,Cordova,Phonegap Plugins,Localnotification,我每天都试图使用我在github找到的LocalNotification插件从我的应用程序发送通知。我有以下代码,它在应用程序启动时立即发送通知 var notification = cordova.require("cordova/plugin/localNotification"); document.addEventListener('deviceready', onDeviceReady, false); functio
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
您的通知每天都会在那里
final AlarmManager am = getAlarmManager();
...
if (repeatDaily) {
am.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, AlarmManager.INTERVAL_DAY, sender);
} else {
am.set(AlarmManager.RTC_WAKEUP, triggerTime, sender);
}
如果查看该类,您可以看到该参数设置的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);
}
课堂上解释的一个额外细节是,如果您为上一次设置时间(例如,现在是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
param。在您的示例中,您使用的是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);
谢谢你的回复。我已经按照你的建议编辑了我的代码。现在,我将其编码为每天早上7点重复发送通知。我在朋友的电话里试过了。这是我第一次使用它,但当我打开应用程序时,它会在同一天重复使用。这背后可能的原因是什么?除此之外的可能原因可能是每次应用程序运行时您都在调用代码。您应该只调用它一次来设置它,而不再调用它。为了安排它,我需要在“ondeviceready”事件之后调用函数。这就是我所做的,看起来很好。今天早上7点闹钟响了。也许我之前提到的问题只是一次性的。谢谢你!!问题是你设置为设备就绪,但每次打开应用程序时,设备就绪运行一次。那不是你想要的。您希望它只在第一次打开应用程序时运行!是的,但是我找过了,但是没有用。很少有其他人也在deviceready回调中实现了它。