简体   繁体   中英

repeating local Notifications automatically?

So I've managed to create a local notification in android. Part of the code is given below.

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),alarmManager.INTERVAL_DAY,pendingIntent);

Now no problem with creating the notification. The thing is that I am currently testing it with a button press which starts the whole notification thing with the Notification appearing every day at the the same time. But, still I don't want to add a button for users to press so I'd have to remove the button and just run this alarm initiation code every time the user starts the app (on Main class' onCreate) just to make sure that notifications are activated. Yet, it does not seem proper to me to set the same alarm over and over since a single time would be enough. Does it actually cause any problems to be doing that continuously ? Or is there any way to get the current activated ALARM SERVICE ? (how?). I was thinking about using shared preferences for a single time activation, but the Service might be stopped in the meantime and no more notifications then. What do you suggest in such a scenario ? I have seen some other posts with nearly same question but it doesn't relate to mine.

"is there any way to get the current activated ALARM SERVICE ? (how?)" Long story short, No you can't directly from Android (you can do it with the shell, while debugging OR if you have rooted your device, in this case, yes).

BUT, good news: an alarm is fully defined by its pending intent, hence, same pending intent, same alarm. What you can do is to call your alarm each time you open the main activity with the same EXACT pending intent. at this point you have 2 choice about the flag of the pendin intent: you can use PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_UPDATE_CURRENT.

The first one will get lunched with the alarm and, if there's one corresponding pending intet allready registered, will simply do nothing (cancell the request leaving the current one)

The second one will get lunched with the alarm and, if there's one corresponding pending intent already registered, will update the present alarm and won't add a ton of alarms each time you open your app.

Personally, the second one has always done his job for me

(see https://developer.android.com/reference/android/app/PendingIntent.html )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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