Scheduling a notification? - java

Is there any way to schedule a notification to appear at a specific time?
I am developing an app that reminds a user to change their bandage every 6/12 hours and I wish to send a notification to the user 6/12 hours after they confirm that they have applied the bandage.
Is there any way to do this? I have tried to implement the alarmManager Class however every example I have found uses a specific time of the day as opposed to 6/12 hours after an event.

I have an app which checks whether to show a notification every 24 hours. You can change it to whatever interval you would like.
with(context.getSystemService(Context.ALARM_SERVICE) as AlarmManager) {
// Create a PendingIntent which AlarmManager would raise.
// You should have a BroadcastReceiver to receive the intent and send a push notification.
setInexactRepeating(
AlarmManager.RTC_WAKEUP,
startAt.toEpochSecond() * 1000,
intervalInMillis,
pendingIntent
)
}
startAt -> Epoch when your alarm should start working (preferably in future). If this is in past, it will immediately boradcast the intent.
intervalInMillis -> Interval in milliseconds. For your case this should be 6 hours.
If your app requires different alarms (notifications) at 6 and 12 hours, I would still go with 6 hours or even 3 hours as the interval. When the broadcast is received, you should check if the app is supposed to send a notification or not. If not, don't do anything.
Read more about Scheduling repeating alarms.
Note: AlarmManager is affected by doze mode and you need to reset all your alarms after the phone restarts. Clubbing this with WorkManager would be ideal. But this should get you started.

Schedule tasks with WorkManager
https://developer.android.com/topic/libraries/architecture/workmanager/
Previously firebase-jobdispatcher-android was working fine now google introduced new WorkManager for scheduling task.
Here is a simple implementaion
http://thetechnocafe.com/how-to-use-workmanager-in-android/

Related

Ways to work around the Android workManager 15 minute minimum interval?

The game I am working on is a missile-oriented GPS-based combat game on Android. The app checks every 15 minutes to see if the user is under attack by any other players, and if so, sends them a notification that they are under attack. Currently, because of the minimum 15 minute interval, the app sends these notifications either too late or not at all. What I need to do is alter this so that somehow, some way, the app checks the "under attack" status of the user more often than 15 minutes. Every minute or every 30 seconds would be ideal.
here is the doWork() method which starts the notification check:
{
if(!MainActivity.GetRunning())
{
Utilities.DebugLog(context, "AlertService", "Main activity not running. Firing notification service handler.");
NotificationServiceHandler handler = new NotificationServiceHandler(context);
handler.Start();
}
return Result.SUCCESS;
}
WorkManager is not a suitable tool for what you wish to do. You will need to use a foreground service and your own in-process timing engine (e.g., ScheduledExecutorService). That will not work for very long before Doze mode and other power-saving measures take effect, but hopefully your games are only an hour or so long.
Hej theBiscuit,
instead of using WorkManager, you could set up an AlarmManager to wake up the app and check for attacks.
If you want to do it while the app is running, a CountDownTimer could help for short periods of time.

setExactAndAllowOnIdle doesnt trigger right

I have a problem using setExactAndAllowOnIdle. In my AlarmReceiver class I just show simple notification that shows when alarm was triggered and set another, same alarm but hour after.(currentTimeMillis + 60*60*1000). When my phone is in use application works fine, alarms come exactly on time. But when I let it work for few alarms without waking device up, they start to trigger with few minutes delays, or sometimes even exactly on time I wake up my phone.
You probably mean setExactAndAllowWhileIdle().
You didn't tell on which OS are You testing it but probably it's because of Doze Mode.
NOTICE:
Neither setAndAllowWhileIdle() nor setExactAndAllowWhileIdle() can
fire alarms more than once per 9 minutes, per app.
So You can't use this method to set every alarm what probably You doing.
For more information You can go here:
https://developer.android.com/training/monitoring-device-state/doze-standby.html

How does Android handle alarms set for the past

In my application I want to trigger a recurring alarm at about a specified time to check for some conditions and notify the user if necessary.
I'm using the following code to schedule the alarm:
Calendar cal = ...;
...
mAlarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, mAlarmIntent);
I now noticed (because I accidentially had the wrong day in cal) that the alarm would be triggered right away if cal was some date/time in the past.
So let's say it is 2016-09-20 18:00:00 and I schedule the alarm for 2016-09-20 17:00:00. I'd get a notification right away (or a couple of seconds after scheduling the alarm). This does not happen if I schedule the alarm for a future time like 2016-09-20 18:15:00.
So my questions are:
Will Android always catch up on the missed alarm?
The alarm is scheduled to repreat daily. Will it then repeat at 17:00:00 tomorrow or will it be at 18:00:00, because that was when the alarm was last triggered?
Will Android always catch up on the missed alarm?
if the set time is in past then android trigger alarm as soon as possible. check the docs
The alarm is scheduled to repreat daily. Will it then repeat at
17:00:00 tomorrow or will it be at 18:00:00, because that was when the
alarm was last triggered?
Next time it will be triggered on time
Additional Info : if the use clear app data or forced close your app from application manager then alarm won't trigger until user open your app again plus reboot can also cause this.

Android: keep timer running when app closed

My app needs to update its data every 24hrs. The user should not be able to access some parts of the app if its out of date.
When the app starts up, I check if the database is out of date. But, the users might keep the app open of in the background for a long time, and I need to alert them when the update is required.
What's the best way to do this? My Initial thought was to use some kind of Handler thread and save a timestamp somewhere every time the app was paused, and then calculate the new time and restart the timer on resumer.
This leaves two questions:
How can I detect whenever my app is paused or resumed, regardless of activity?
And what is the best idiom for a long-running timer in Android? (keeping in mid that it has to be able to modify UI components ie show an alert when he time is up)
You could do that, but you should not, instead store the time stamp in the shared preferences whenever the app get closed, when open again read that value again and calculate the difference by getting the actual timestamp.... then after that update if necessary the lapsed time!
timeStamp is just a long value..
and you can get it by just calling the System.currentTimeMillis()
and for the shared preferences use the Class SharedPreferences
You can have a Service do the query every 24 hours for you and notify the user if it fails. You can use the AlarmManager for that. Eg:
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent m_intent = new Intent(this, YourService.class);
PendingIntent pi = PendingIntent.getService(this, 2, m_intent, 0);
alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000 * 24 * 60 * 60, pi);
The Service can then ask the AlrmManager to call itself after 24 hours again using the above code only.
NOTE: Alarms can be cancelled by the system or the user (force stop). So, this solution comes with its caveats.

AlarmManager skips alarms set using set() / setExact() in a 48hrs+ cycle

In an app I have to regularly sync data to a server which happens at a fixed interval (mostly) of 5mins.
I am using set() / setExact() depending upon if Build API >= 19. Now, for most of the time the alarm gets fired and does it's job but intermittently (even during daytime) the alarm isn't getting fired.
The alarm manager is passed a pendingIntent for an IntentService which does the sync work.
And in onHandleIntent I am also running my setSchedule() which in turn sets an alarm to get fired after 5 mins(same as above^).
Using Alarm Type of RTC_WAKEUP (until now; I've recently changed it to elasped realtime + wakeup and waiting on for some test results)and the HTTP connection and socket timeout of 30secs each. The device was not restarted in between the 48hrs+ (as a sample case) duration as I don't miss any captured data it's just that the sync alarm skips somehow.
I am starting to doubt if this is a wakelock issue :|
Has anyone faced any problem with Kitkat's setExact() ? AFAIK, the way it is (except for using the RTC/elasped realtime change) the current way shouldn't be skipping on the alarms.

Categories

Resources