Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

解決通知欄項目上下跳動閃爍的問題

編輯:關於 Android 程式設計

有一類 bug 特別惱人:功能都正常,但正在進行的通知項在通知欄裡一直上下竄動、不停閃爍。原因不在邏輯,而在一個幾乎沒人會在意的屬性。

問題代碼

notification.when = System.currentTimeMillis();

看起來天經地義——通知的時間當然是當前時間。但這正是問題所在。

原因

when 的默認值就是「現在」。當我們每次刷新通知時都重新賦一次當前時間,這個值就在不斷變化。而系統的通知欄會依據 when 對通知進行排序,時間戳一直變,排序位置自然一直變,視覺上就表現為上下跳動。

正確的做法是:對於一個持續存在的通知,when 應該在 Activity 啟動時就固定下來,後續更新只改內容,不動時間。

解法

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

實踐中通常取業務開始的時刻並存為成員變量,比如文件下載開始的時間、計時器啟動的時間,這樣既穩定又語義準確。

官方文檔怎麼說

Android 對 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. 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 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.
- Notification of an ongoing stopwatch should be stamped with the watch's start time.
- Notification of an ongoing countdown timer should be stamped with the timer's end time.

把這幾條例子放在一起看,規律就非常清楚了:有限事件(消息到達、下載完成、會議即將開始)取事件本身的時刻;無限持續事件(正在進行的下載、跑著的計時器)取活動開始或結束的固定時刻,而不是「每次刷新的此刻」。

換句話說,when 描述的是「這條通知講的是什麼時候的事」,不是「這條通知是什麼時候更新的」。把這兩者混為一談,就會得到一個不停跳動的通知欄。

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

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