如何获取与设备无关的本地日期和时间的Android [英] How to get device independent local date and time Android

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

问题描述

我的应用程序是时间相关的,我不希望设备日期和时间的变化影响我的应用程序,就像用户故意将设备日期设置为任何先前的日期一样。当用户连接到移动网络或WiFi时,是否有任何方法可以获取当前日期和时间?我不想使用GPS。

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.

推荐答案

SystemClock 类的

Javadoc描述了计算经过时间的不同方法

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();




返回自系统启动以来的时间,并包括深度睡眠。
该时钟保证是单调的,并且当CPU处于省电模式时,即使
仍会滴答作响,因此
通用间隔定时的推荐依据也是这样。

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();

接下来,您可以将毫秒转换为String,例如:

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

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

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