Android - 在不依赖设备时钟的情况下获取当前时间 [英] Android - Get current time without dependency on device's clock

查看:10
本文介绍了Android - 在不依赖设备时钟的情况下获取当前时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 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.

如果你不需要实际时间而只是一个不能乱搞的时间,你可以使用SystemClock.elapsedRealtime() 为您提供自设备上次启动以来的时间.

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 值)定时器服务器值).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆