亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取應用程序關閉的時間。如何?

獲取應用程序關閉的時間。如何?

慕標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 關注
  • 266 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號