-->

How to get device independent local date and time

2019-07-15 11:42发布

问题:

My application is time dependent and I don't want change in device date and time affect my application, like if user deliberately set device date to any previous date . Is there any way to get current date and time when user is connected to mobile network or WiFi I don't want to use GPS.

回答1:

Javadoc of the SystemClock class describe different ways of counting elapsed time for various scenarios and conditions.

In your case you have to use

long time = SystemClock.elapsedRealtime();

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.

Call it for the first time when you want to start tracking the use of Network (I assume you already know how to do it) and store that value.

When you receive event about user not using network anymore, call the same method again and calculate spent time.

long elapsed = time - SystemClock.elapsedRealtime();

Next you can transform milliseconds to String for example like this:

String formattedElapsedTime = DateUtils.formatElapsedTime(elapsed/1000);//note that this method takes second as arguments so we have to divide it by 1000


回答2:

You should call webservice and get current date and time of server. Then server would be responsible for the actual date/time. Best way is to build your own webservice, because it gives you more control than using third party.