repeating local Notifications automatically?

自闭症网瘾萝莉.ら 提交于 2019-12-11 17:44:03

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/48251736/repeating-local-notifications-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!