当设备离线时,如何获取正确的Android设备当前日期和时间 [英] How can I get correct current date and time for android device while device is offline

查看:749
本文介绍了当设备离线时,如何获取正确的Android设备当前日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个Android应用程序,在这个应用程序中,用户可以保存一些任务。这些任务保存在设备中,当用户上线时,任务将与服务器同步。
我现在需要用户保存任务的正确日期和时间。代码如 Calendar.getInstance() new Date()返回设备时间,如果设备时间不正确,任务保存在错误的日期。这个应用程式可以离线工作很重要。而且由于这个应用程序的流行性,用户可以有目的地更改设备时间。
对不起,我的英文不好。

I create an android app and in this app, users can save some tasks. Those tasks are saved in device and when user go online, tasks will sync with server. I need to now the correct date and time when user save the task. Codes like Calendar.getInstance() or new Date() return device time and if device time was not correct, task save with wrong date. It's important for this app to work offline. And Because of bushiness of this app, It is possible to user change device time in purpose. Sorry for my bad English.

推荐答案

所以我结束了这种情况,大多数连接到互联网每次设备重新启动一次。

当用户启动时,我尝试连接到NTP服务器( BOOT_COMPLETED BroadcastReceiver )或网络状态更改( CONNECTIVITY_CHANGE和WIFI_STATE_CHANGED BroadcastReceiver ),然后我存储该日期和 SystemClock.elapsedRealtime() / code>在数据库中。之后,我想要有正确的日期,我只是得到新的 SystemClock.elapsedRealtime()并计算这个值和从数据库的elapsedRealtime值的差异,并添加到目前为止,我存储在数据库中的差异。

I try to connect to a NTP server when user boots (BOOT_COMPLETED BroadcastReceiver) or Network states changed (CONNECTIVITY_CHANGE and WIFI_STATE_CHANGED BroadcastReceiver) and then I store that date and SystemClock.elapsedRealtime() in the database. After that when ever I want to have the correct date, I just get new SystemClock.elapsedRealtime() and calculate the difference of this value and the elapsedRealtime value from database and add that difference to date that I store in database.

这篇关于当设备离线时,如何获取正确的Android设备当前日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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