tags:

views:

57

answers:

2

Hello In my android application i would like to get Time since when the app is opened. Initially what i tried was getting the time when the app is loaded from the server and then taking the difference with the current time from the device.But by doing that if the user changes the time then i willnot be getting the actual time. Its not posiible to hit the server again for the same.

Is there any way to achieve this in android?

Please share your valuable suggestions.

Thanks in advance:)

+1  A: 

Try SystmeClock class

uptimeMillis() method store var in app that reads that when app starts

Fred Grott
For real time you actually want SystemClock.elapsedRealtime(). For most uses uptimeMillis() is correct, but it is not actually real running time. http://developer.android.com/reference/android/os/SystemClock.html
hackbod
+1  A: 

Echoing what I said for your other question, you first need to become familiar with the activity lifecycle and understand the novel meanings (almost meaninglessness) of common words like "open" and "start" in the life of an android app.

There isn't any way you can prevent the user from changing the system time - you just don't have the right to do that to users. Normally this should be a rare event, unless you do something that makes them want to, such as lock them out of a free version of your app after so many minutes. (However if the phone is on a mobile network, presumably the mobile network occasionally adjusts its time to correct for errors in the device's oscillator, or administrative time changes)

What you can do is check the system time on every entry point to your application. If it ever goes backwards, well... something is going on. If the clock has been set back, you could assume no time between the calls with the negative time difference and resume your time meter from there, at least keeping all the previous used time in your record.

It may be that there are cpu cycle counters which you could query and correlate to system time, but this may be highly device specific and may in fact be resettable. And it may get weird if the cpu frequency is demand throttled.

You might be able to set a countdown timer as a bound on the maximum possible time between entry points at which you could meter. I don't know if these work reliably across system time changes or not - ideally they would. Testing or reading the source will reveal.

Chris Stratton