gpt4 book ai didi

android - 获取新旧时间的区别

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:53:21 25 4
gpt4 key购买 nike

我需要知道新旧系统时间之间的差值(在用户更改后)

使用以下代码我可以捕捉到用户更改时间的时刻:

<receiver android:name=".TimeChangeReceiver">
<intent-filter>
<action android:name="android.intent.action.TIME_SET"></action>
</intent-filter>
</receiver>

public class TimeChangeReceiver extends BroadcastReceiver {
private static final String TAG = TimeChangeReceiver.class.getSimpleName();

@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "changed time: " + new Date(System.currentTimeMillis()));
}
}

例如当前时间 10:00,用户将其更改为 11:00 - 调用了 onReceive 方法,但时间已经更改,如何获取之前的值 - 10:00?

最佳答案

下面是计算先前值的解决方案。我试过了,你可以在这里找到我的实现 https://github.com/chrisport/setTimeIntent

主要思想是这样的:你需要一个独立的时间来比较,我们可以采取SystemClock.elapsedRealtime() 这是自设备启动以来的时间。现在我们可以计算这个 elapsedTime 和 System.currentTimeMillis() 之间的差异。这种差异将始终保持不变,除非 SystemTime 已更改(例如,由用户更改)。在这种情况下,我们可以计算出新的差异并将它们进行比较以确定它改变了多少

让我们开始吧:

  1. 计算电流差:

    public static long getCurrentDifference() {
    long elapsedTime = SystemClock.elapsedRealtime();
    long currentTime = System.currentTimeMillis();
    return currentTime - elapsedTime;
    }
  2. 在开始时将此差异存储*到 SharedPreferences

  3. 当收到SET_TIME时,计算当前差值与存储差值的差值

    long lastDifference = mySharedPrefs.getLastTimeDifference();

    //Calculate the new difference
    long currentDifference = getCurrentDifference();

    //Calculate the difference of the differences
    //this is the change the user made
    long userChangeInMillis = lastDifference - currentDifference;

    //and here we get the old time:
    long previousTime = System.currentTimeMillis() + userChangeInMillis;

您还可以从中创建一个日期 (new Date(previousTime))。

*要始终有一个初始时间差,您可以在应用程序打开时将其存储到 SharedPreferences,当设备启动时(需要另一个 BroadCastReceiver),以及在收到 SET_TIME 后保存新计算的差值。

编辑:

我的示例的输出如下所示:

Before it was Wed May 21 17:43:28 GMT+00:00 2014
Now it is: Wed May 21 18:43:00 GMT+00:00 2014

不知何故 SET_TIME 被接收了两次。因此有两个日志消息,第二个显示当前时间的两倍,因为我用新计算的一个覆盖了 lastDifference。

关于android - 获取新旧时间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23785770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com