Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 通知欄持續跳動閃爍的原因與解法

編輯:Android 開發實例

曾遇到一個惱人的問題:程式裡的通知一切正常,唯獨「進行中」的那一條總是上下跳動、一閃一閃,使用者體驗很差。查過之後才找到癥結。

問題出在 when 屬性

原本的程式碼是這樣寫的:

notification.when = System.currentTimeMillis();

這正是元凶。對通知而言,when 應該在該通知所對應的事件開始時就固定下來;若沒有明確設定,系統會採用預設值,也就是「當下時間」。於是每次通知被刷新,時間戳也跟著變動,排序位置與顯示內容自然就不斷跳動。

解法:給一個固定的時間戳

final long TIMESTAMP_FIXED = 1234567890l;
notification.when = TIMESTAMP_FIXED;

實務上會直接把「計時開始的時間」存起來重複使用,而不是寫死一個常數。

官方對 when 的說明

A timestamp related to this notification, in milliseconds since the epoch. Default value: Now. Choose a timestamp that will be most relevant to the user. For most finite events, this corresponds to the time the event happened (or will happen, in the case of events that have yet to occur but about which the user is being informed). Indefinite events should be timestamped according to when the activity began. Some examples:

  • Notification of a new chat message should be stamped when the message was received.
  • Notification of an ongoing file download (with a progress bar, for example) should be stamped when the download started.
  • Notification of a completed file download should be stamped when the download finished.
  • Notification of an upcoming meeting should be stamped with the time the meeting will begin (that is, in the future).
  • Notification of an ongoing stopwatch (increasing timer) should be stamped with the watch's start time.
  • Notification of an ongoing countdown timer should be stamped with the timer's end time.

歸納起來就是一句話:無限期持續的事件,應該以「活動開始的時刻」作為時間戳,而不是每次更新都重取一次當前時間。

參考資料:https://developer.android.com/reference/android/app/Notification.html#when

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved