Android-获取当前时间而不依赖设备的时钟 [英] Android - Get current time without dependency on device's clock
问题描述
我注意到System.currentTimeMillis()时间与设备有关.如果我更改设备时钟上的时间,则此方法将返回不同的答案.
例如:如果现在的实时时间是10:00,并且我将设备上的时钟更改为9:30,则System.currentTimeMillis()将返回9:30时间(以毫秒为单位).
我也尝试了此答案和其他一些答案,但没有发现任何有用的方法.
我应该声明我的应用程序大部分都可以离线运行.
有没有一种方法可以在没有外部API的情况下获得实时时间(与设备无关)?
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.
您还可以将时间服务器和SystemClock.elapsedRealtime()结合使用:一次(例如,在启动后)从计时器服务器中获取时间,然后从该时间值中将elapsedRealtime()添加到该初始值(减去获得时的elapsedRealtime值). timerserver值).
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).
这篇关于Android-获取当前时间而不依赖设备的时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!