I've noticed that System.currentTimeMillis() time is device dependent. If I change the time on the device's clock, this method will return a different answer.
For example: If the real time now is 10:00, and I change the clock on my device to 9:30, then System.currentTimeMillis() will return the 9:30 time (in milliseconds..).
I've also tried this answer and some other answers, but didn't find anything useful.
I should state that my app works mostly offline.
Is there a way to get the real current time (device independent) without external API?
If it were not for the 'offline' part, I'd have suggested to use a time server, but given that your app is offline most of the time that might not be a good solution.
If you don't need the actual time but just a time that cannot be messed with, you can use SystemClock.elapsedRealtime() which gives you the time since the device last booted.
You could also combine time server and SystemClock.elapsedRealtime(): Fetch the time from timer server once (e.g. after bootup) and from then on add elapsedRealtime() to that initial value (minus the elapsedRealtime value of when you get the timerserver value).
If you use the GPS location provider, getTime() will return the UTC time derived from the GPS signal, rather than the device time. The GPS location provider can work offline - but it will be much slower to obtain a fix compared to being online when it can access the A-GPS info.
Related
I'm seeing in docs that the object Location has a method getTime().
In my app, I need the server time, but sometimes, app can be offline, so I have no choice to get cel time. I would gladly use Location.getTime, but it is not clear to me where this time is coming from?
The Cel or the GPS Satelite???
Is it a reliable data for getting the current hour when app is offline?
As discussed in this question, Location.getTime() returns either
the device time (System.currentTimeMillis()) if Location.getProvider().equals(LocationManager.NETWORK_PROVIDER)
or
the GPS (satellite) time (in milliseconds but with 1s precision) if Location.getProvider().equals(LocationManager.GPS_PROVIDER)
Since the GPS location determination is based on the knowledge of the precise time, I would say it is at least as reliable as the time you would get from a server.
You can apply your local time zone to the GPS timestamp to get a human readable time, which sould be equal to a properly synced device time (in my case most of the devices where not, so it was even better to use the GPS time).
It is useful when you don't need a very precise time and you just want to know the date only regardless to precise time. Since as the documentation says:
All locations generated by the LocationManager are guaranteed to have
a valid UTC time, however remember that the system time may have
changed since the location was generated.
Also take a look at getElapsedRealtimeNanos() it seems to be more precise.
I found what was wrong:
So apparently http://www.epochconverter.com/ is makes assumptions of the precision of the input values, and from those assumptions values around 841073068 goes to 1996/1997. I'm not sure what is the assumption that leads to that exact date, but honestly I don't care.
Using the attached debugger I called new Date(System.currentTimeMillis()) and it correctly gave me a 10th Jan-1070 date, meaning the clock is not jumping out of the way like crazy.
Original question:
I'm running a single-board computer with Android for and IoT case (this https://developer.qualcomm.com/hardware/dragonboard-410c). The OS running is the plain vanilla Android supplied by Qualcomm.
Currently I'm testing the reliability of the board to be left executing for long periods at once and I'm seeing some very very weird behavior that I can't find an explanation for.
The board was powered up 10 days ago and it have no access to internet (WiFi is on but no access point setup and no Ethernet). The bluetooth is on and there're iBeacons and Eddystone in the office. Also there are WiFi in the area.
If I go now to Settings -> Date and Time, or check the notification shade or enter the clock app, or the calendar app, I see 10th of January 1970. Which is expected and basically showing for how long the board been running.
The app on it have an always running service, which does some data processing and some disk-logging (for debugging).
From the logs, I can see that System.currentTimeMillis() was returning an expected value when the board was initially powered on. That means, the beginning of the logs indicate an epoch time in January 1970.
But at the end of the logs (and also attaching the debugger on the live process), the value of System.currentTimeMillis() is somewhere in Sep/Oct 1996. Example values: 841073068, 841263234, 841579239
So my question is:
What is happening here?
Why System.currentTimeMillis() value changed and what could have changed it?
Why the Android UI (notification, clock app, settings) still shows me 1970? Where are they getting this value from?
edit:
There's been some confusion on the answers, and I can see my question was lacking the details.
I do not want to measure difference of time. I need an actual time stamp. Those values will be reported with bluetooth LE events via POST to our backend. This "no network" thing is a reliability test that we're running on the board, but we do expect to have network most of the time, and the boards should auto-update their times from network using the normal Android ways.
I'm just trying to understand on the current batch of testing, what went wrong and why.
Well, as you already know, the current system time (System.currentTimeMillis()) can be modified by any process if desired, it's perfectly be possible that it was modified by another process. It's not a reliable method to measure up-time.
I would rater use something like:
SystemClock.uptimeMillis()
Which returns the elapsed time (in milliseconds) since the device booted (not including time spent in deep-sleep).
I would also like to mention that I suspect that Bluetooth has something to do with it, I can imagine that Bluetooth uses the system time for pairing and security just like SSL does (but I'm no expert). GPS could also be a problem as GPS can be used to obtain an UTC time value, but I'm not sure if your board has a GPS module.
Regarding your edit:
Obtaining a valid time-stamp would be quite easy: server time minus the elapsed time reported by your board. But I suggest you either choose to accept the time reported by System.currentTimeMillis() or use the elapsed time instead. At the company I work we also work with embedded Android devices and on our server dashboard we can see both the up-time (up since) and the current device time, but they should not be mixed, at least in my opinion, especially since System.currentTimeMillis() is subject to changes and is affected by summer and winter time.
If you want to measure something, better try System.nanoTime(). Here is difference - https://stackoverflow.com/a/351571/2793494
I need to measure long elapsed time on Android and there may be device reboots in between.
From what I've understand, System.nanoTime() is resetted every time the device reboot, and System.currentTimeMillis() is unreliable because user can change it.
The only solution that I came up with is to listen to ACTION_SHUTDOWN and BOOT_COMPLETED, use System.currentTimeMillisec() to calculate the elapsed time (user can't change clock time while the device is off, hopefully :) ) and add it to the last System.nanoTime() I had before shutting down.
I honestly don't like this solution because it's very expensive (I need to listen to 2 broadcast events) and inaccurate, but I couldn't figure out any other way to do this.
Any ideas? Also a native solution would be good for me.
You can get around the user changing time by using an internet time server to get the times when you check. There are a couple of ways to do this.
Get it via NTP server
How to get current time from internet in android
How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?
Get it via HTTP header
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Responses ( see Date header )
If you simply persist this value then the user can do nothing to mess up your calculation.
I'm doing a camera application that will automatically geo-tag each picture taken. Using
LocationManager.requestLocationUpdates() //simply to get the GPS running
LocationManager.getLastKnownLocation() //for each picture, to get coordinates
is mostly enough to simply pluck out coordinates from the phone as fast as possible, since it is still a camera application and you don't want to waste time getting GPS data.
(Assume using GPS_PROVIDER only, not NETWORK_PROVIDER pls)
However the issue will be if the user enters a tunnel for example and the phone is unable to continue getting updates. 10 minutes later when getLastKnownLocation() is called, I will get an outdated location.
I want to find a way in which I can set an 'expiry' time on the Location, depending on individual comfort level.
In other words, keep using getLastKnownLocation(), but if the data is (for example) more than 5 minutes old, don't bother with it, and I rather have a 'null' location. if the data is 2 minutes old however, that still is fine
You can implement this yourself. There's nothing in the underlying API that includes this, but it's perfectly fine to stash the time that you initiated the request (or got the last one) in your app, perhaps in a SharedPreferences. You also have to be weary of things like how fast the user is moving, etc.., so in general you might need to put a fair amount of thought effort into determining how you want to do this. There's not any way (in the API) to find out how fresh the call to .getLastLocation() will get you. For a few minutes it's probably best to employ the technique I mentioned. For a lot longer you might want to consider something like an AlarmManager (which you should be using anyway if your app runs on a timescale that is that long). You seem to be using .getLastLocation more than I do, however. I often simply just request updates and then "put the dot down" whenever I get the first update. In general I've found that .getLastKnownLocation() isn't really all that reliable, but maybe that's just because I don't use apps with my location very often.
Managed to find out that each Location returned had a time variable
long time_a = my_loc.getTime();
We can use this to compare with
Calendar cal = Calendar.getInstance();
long time_b = cal.getTimeInMillis();
long interval = time_a - time_b;
The interval is then the 'validity' of the location fix, and can be easily used for my purpose :)
My app uses LocationListener to keep track of the current location. So long as the GPS Provider is providing regular fixes this works well. However, I want my app to alert the user if the location is no longer reliable because the fix is no longer current. I have therefore used a timeCheckHandler to call getLastKnownLocation every few seconds.
My problem is that even when accurate fixes are being received frequently the time returned by applying getTime() to the location returned by getLastKnownLocation is generally older than the current time returned by System.currentTimeMillis(), often by about 20 seconds.
I have investigated the problem further by adding code to onLocationChanged(arg0) to log the time of the fix (arg0.getTime()) and the current time (System.currentTimeMillis()). Again I see a difference of about 20 seconds.
The code currently reads as follows:
public void onLocationChanged(Location arg0) {
mapview.handleLocationChanged(mapview, arg0.getLatitude(), arg0.getLongitude(), arg0.getBearing(), arg0.getAccuracy(), "GPS fix");
addDebugNote("Fix received at time: "+Long.toString(arg0.getTime()/1000)+" Now: "+Long.toString((System.currentTimeMillis())/1000));
}
and typical output to my Debug file reads:
Fix received at time: 1292091908 Now: 1292091928
Why should I be seeing this difference between the fix time and the current system time?
Do I have to accept that a difference of around 20 seconds is normal?
GPS location time comes independently of your network provider time/device time. System.currentTimeMillis() will give you device time set on your device.
If you want to know how recent the point is you can:
Synchronize both the times ( GPS and device ) in your code at application start by taking the difference between both as soon as you get first GPS location update. At that instant query device time and see what's the difference in both. Save this difference in variable.
Use this as a correction factor in subsequent location updates to know the exact time based on the reference frame you need. ( Device time or GPS)
Also I had found that using NETWORK as location provider you may get device time only. So if you are listening on updates from both ( GPS and network ) , you may also need to distinguish this using location_obj.getProvider() and filter out GPS provider.
Repeating the test today I have found that the difference between the GPS time and the System time is 22 seconds. This issue is discussed elsewhere on the web and it seems that it is normal for there to be a difference between GPS time and the phone's system time (which in my case is set to be updated automatically from the network.) One factor is that GPS time is about 15 or 17 seconds (depending on which source is correct) from UTC time ... it is out-of-sync because GPS time has not been updated since 1980 for periodic "leap seconds."
Bearing this in mind I think the answer to my need to check how current the latest fix is will be to compare the current system time with the system time (not the GPS time) of the latest fix.