为了账号安全,请及时绑定邮箱和手机立即绑定

获取应用程序关闭的时间。如何?

获取应用程序关闭的时间。如何?

慕标5832272 2023-08-23 17:02:00
我想制作一款空闲游戏,为此我需要获取应用程序关闭的时间,以便我可以计算该离线时间内的收入。我的第一个想法是获取 currentTimeMillis 并通过共享首选项保存它们,当再次打开应用程序时,我计算当前时间和保存时间之间的差异。我的问题是sharedPreferences变量似乎一直是0。我的代码:Zeit = System.currentTimeMillis() / 1000L;Zeit_Differenz = Zeit - Zeit_SAVE;        Log.i("e","aktuelle Zeit: " + Zeit);        Log.i("e", "gespeicherte Zeit: " + Zeit_SAVE);        Log.i("e", "errechnete differenz: " + Zeit_Differenz);SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);SharedPreferences.Editor editor = sharedPreferences.edit();editor.putLong("Zeit save", Zeit);editor.apply();SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);Zeit_SAVE = sharedPreferences.getLong("Zeit save", 0);日志猫:aktuelle Zeit: 1569344292                         (time right now)gespeicherte Zeit: 0                              (saved time)errechnete differenz: 1569344292                  (calculated difference)这些片段之间还有其他代码。我刚刚为您复制了最重要的代码。我希望你能帮助我,这确实是我如何实现这一目标的唯一想法。
查看完整描述

2 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

只需重写方法Activity.onPause()Activity.onResume()保存时间戳,然后再执行计算。首选项名称中的一个空格Zeit save可能会导致它始终返回默认值0;最好用_下划线替换它,例如。timestamp_paused



查看完整回答
反对 回复 2023-08-23
?
不负相思意

TA贡献1777条经验 获得超10个赞

博士

我无法帮助将值保存到存储中,因为我不使用 Android。但我可以展示如何记录当前时刻并稍后计算经过的时间。

记录当前时刻。

Instant.now().toString()

"2019-09-24T20:50:52.827365Z"

解析该字符串并捕获经过的时间:

Duration                                              // Represent a span-of-time not attached to the timeline.

.between(                                             // Calculate time elapsed between a pair of moments.

    Instant.parse( "2019-09-24T20:50:52.827365Z" ) ,  // Parse string in standard ISO 8601 format. The `Z` on the end means UTC, pronounced “Zulu”. 

    Instant.now()                                     // Capture the current moment in UTC.

)                                                     // Returns a `Duration` object. 

.toMillis()                                           // Interrogates the `Duration` object for its total elapsed time in milliseconds, effectively truncating any microseconds/nanoseconds.

java.time

跟踪时间的现代方法使用java.time类,具体来说:

  • Instant代表 UTC 中的某个时刻

  • Duration表示与时间线无关的时间跨度,基本上是纳秒的计数。

捕获 UTC 中的当前时刻。

Instant instant = Instant.now() ;

使用标准ISO 8601格式保留该值的文本表示形式。

String output = instant.toString() ;

读取存储的字符串,并将其解析为Instant.

String input = "2019-09-24T20:50:52.827365Z" ;
Instant then = Instant.parse( input ) ;

捕获当前时刻,并将经过的时间计算为“持续时间”。

Instant now = Instant.now() ;
Duration d = Duration.of( then , now ) ;

如果您希望将经过的时间作为总毫秒数,请询问该Duration对象。

long milliseconds = d.toMillis() ;  // Total elapsed time in milliseconds, truncating any microseconds/nanoseconds.
查看完整回答
反对 回复 2023-08-23
  • 2 回答
  • 0 关注
  • 107 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信