AlarmManager alternatives for persistent frequent scheduling - java

It has come to my attention that Android 5.1 no longer accepts recurring alarms for time intervals shorter than 60 seconds (source).
I am developing an application that logs information about wireless networks. For the operation of the application it is imperative that it can perform its operations every 1-2 seconds and that it doesn't get killed or suspended by the operating system even if it is using a lot of resources. Reliable operation over long periods of time (several hours) is the most important thing. Impact on battery life is not a concern.
So far the most reliable way of achieving this functionality has been to use recurring alarms. Now with Android 5.1 that is no longer an option. What would be my best options for replacing the AlarmManager implementation?

As a workaround you can set up 60 alarms to get flexible solution for your current implementation. Check OS version and set up as many alarms as you need.
But for a long-term solution I suggest you to implement sticky foreground service which would work similar to music player. Something simple like Handler.postDelayed should be enough to keep it alive. The reason to do this way is that alarms are not accurate and it is always better to have some control on the process.

Related

Issues with long running Handlers, Timers, and Tasks?

I've seen a number of questions using the Handler or Timer implementations in Android apps to delay an update to the UI thread. Most of these seem to be short - a few seconds at most.
Are there issues with using a 24 hour delay for a task? How does Android handle very long running Hander and Timers?
Are there issues with using a 24 hour delay for a task?
It won't work reliably.
A Handler, or any other in-process timing option (e.g., ScheduledExecutorService) is only as good as the process that is hosting it. Once the process goes away, so does the timing. Android processes normally do not live for 24 hours.
If it makes you feel any better, all the other alternatives (e.g., AlarmManager, JobScheduler) will also not work reliably as of Android M, in the interests of power management. However, the alternatives will be efficiently unreliable, since they do not require your process to be constantly running.

Changing time on device => cheating in the game

In some games people can cheat by changing the time. For example: when they have to wait 30 minutes before a building is built.
Can i prevent this, assuming that the devices have connection with my server?
I am programming in java using the libGDX library.
Any solutions that work both on IOS and Android?
Store the time they have to wait to on the server (tell the server they perform a task, server will log that time and when they can do it again) and make the client check if the server thinks it can in fact perform the action. Anytime you store something on the client it is likely that there will be a way around it.
Your best bet would be to use SystemClock.elapsedRealtime() as an assistant to an infrequent server side timecheck.
return the time since the system was booted, and include deep sleep. This clock is guaranteed to be monotonic, and continues to tick even when the CPU is in power saving modes, so is the recommend basis for general purpose interval timing.
After verifying the time from your server, you can do local checks against SystemClock.elapsedRealtime until the next boot up.

Using Timer.scheduleAtFixedRate() in Android

In my Android app, I need a certain bit of code to execute every minute, whether the phone is active or not.
(For those curious, the app is meant for a personal project, a "talking" clock which will need to check every minute if that time has a corresponding sound file to play. It's not something I plan to release to the world, so battery considerations are not in play.)
My current approach is to use Timer.scheduleAtFixedRate() to schedule a task.
This seems to work whenever I am looking at the app, and interacting with it occasionally to keep the screen from blanking, but if the phone turns the screen off to save power, it seems like my call happens sporadically.
I tried setting the interval to be every 30 seconds, but even then it seems like I miss some minutes. Are there specific considerations to using Timer on Android? Is there a better way to achieve what I need?
Question: are you 100% absolutely sure you need to be doing this every minute? It just sounds to me that you'll be hogging the battery like crazy and will get quite a few unhappy users.
But if you answer yes to that question:
After your activity is paused, there's not guarantee from the system that anything on it (including your task) will be kept running; that way as soon as the systems needs a couple of megabytes to do anything it will kill your activity and stop your timer.
You should implement the timer/task in a Service. Services are much less likely to be killed by the system and you might ask that if the system needs to kill it to re-created it as soon as possible.
Have you tried using AlarmManager, this will let you do a task every X amount of time even if the phone is in standby mode or off
Here are the docs for it
If you want a nice example of using an AlarmManager, here it is... This one does not work if the phone is turned off but you can enable this easily if you want

How use NTP server when scheduling tasks in Java app?

I know NTP servers can be used to synchronize your computer's system clock. But can NTP be used by an application that wants to schedule things in sync with other systems?
Scenario: Developing a java app (perhaps to run in an ESB like Mule) and you won't necessarily be able to control the time of the machine on which it will run. Can your app use an NTP server to obtain the time and schedule tasks to run based on that time?
Let's say you're using Quartz as the scheduler and perhaps joda-time for handling times (if that's useful). The time doesn't have to be super precise, just want to make sure not ahead of remote systems by much.
If you're not super worried about drift, and assuming that the machines aren't just randomly changing time, then you could ping an NTP server to get what time IT thinks it is, and compare that to the time your local machine thinks that it is, then calculate the differential and finally schedule your task in local time.
So, for example, say that the NTP server says that it's 12:30, but your local machine says that it is 12:25. And you want your task to go off at 13:00 NTP time.
So, 12:25 - 12:30 = -0:05. 13:00 + (-0:05) = 12:55, therefore you schedule your task for 12:55.
Addenda --
I can't speak to the naivety of an implementation, I'm not familiar enough with the protocol.
In the end it comes down to what level of practical accuracy is acceptable to you. NTP is used to synchronize time between systems. One of the problems it solves is by being continually invoked, it prevents clock creep. If you use the "NTP Ping, schedule with offset" technique, and, say, that future time is perhaps 8 hrs in the future, there's a very real possibility of clock creep, meaning that although you wanted the task to go off at "12:55", when 12:55 rolls around, it could be off from the original NTP server since the clocks have not been synced (at all), and the job has not been rescheduled to virtually resync.
Obviously, the longer the period between original schedule and actual execution, the more the potential for drift. This is an artifact no matter how good the original NTP ping is. If you do not plan on rescheduling these tasks as they get close to execution time in order to compensate for drift, then odds are any "reasonable" implementation of NTP will suit.
There's the Apache Commons NET library that has a NTP client. Some complain that it uses System.currentTimeMillis(), which has (had?) resolution issues (10-15ms) on Windows. System.nanoTime addresses this, and you could easily change the library to use that, and rebuild it.
I can't speak to how it reflects the "naivety" of the implementation. But in the end it comes down to how close you need to keep the two machines and their jobs (virtually) in sync.
My intuition tells me that the NTP requires a hardware clock adjustments to keep a pace. So if you don't have access to the hardware, you cannot do it.
However, if it is enough to have a few seconds precision, you could periodically send sample time from a server to calculate a skew between the system clock and adjust scheduled time for jobs.
But can NTP be used by an application that wants to schedule things in sync with other systems?
I've never heard of it being used that way. However, there's nothing to stop you implementing a client for the Network Time Protocol (RFC 1305). A full NTP implementation is probably overkill, but you can also use the protocol in SNTP mode (RFC 2030).
You probably want to set up and use a local NTP server if you want high availability and reasonable accuracy.
A Google search indicates that there are a number of Java NTP clients out there ...

Stable timer independent of system time

I use java.util.Timer to trigger jobs in my app, but I found that it is depend on system time: if system time is adjusted, timer's trigger will be affected.
For example, if system time goes back by 80 seconds, the timer will stop working for 80 seconds.
Java has a System.nanoTime method which is independent of system time, but it seems that it
cannot be used in Timer.
Is there Timer library that supports what I need? Or I have to implement it myself?
Notice that I don't need a precise current time(date), I need a precise time interval
you have 2 options:
Write your one timer, relatively trivial. Before anyone tell reinvent the wheel, being able to carry the task yourself is always important. Especially when it's around 20 lines of code.
Use java.util.concurrent.ScheduledThreadPoolExecturor and use scheduleAtFixedRate, the queue impl. is based on System.nanoTime.
Install ntp daemon that adjusts the time by tuning (slowing down, speeding up) the system clock in very slight fashion during long time span.
Few other things, perfect 100ms is a tall order in non-real time GC environment as GC may STW (stop the world) for seconds sometimes. Sun's GCs can't do that super reliably. IBM's Metronome running on modified Linux kernel is supposed to be able to. You may wish to pay attention to if your application is truly real-time demanding.
If your computer is isolated and off the Internet i think there is not much you can do if the user tampers with the clock.
On the other hand, if this is not the case, you will find quite many API's and Mashups that will allow you to read the correct time. You could read the time from there. You could read the time from time.gov. Also twinsun.com you give you lots of additional options.
100ms seems like too low for Internet time-access.

Categories