簡體   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