How to get device independent local date and time Android

浪尽此生 提交于 2019-12-13 16:21:38

问题


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.



来源:https://stackoverflow.com/questions/25283040/how-to-get-device-independent-local-date-and-time-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!