Notification 是讓應用程式在不跳出 Activity 的前提下提醒使用者的一種機制,也是行動裝置上最順手的 UI 形式——手機幾乎不離身,App 多半在背景執行,一旦有需要注意的事件,能即時通知就顯得格外重要。
這些都由 NotificationManager 統一管理。若預設樣式不夠用,可以帶入自訂版面,讓提醒的呈現方式完全依你的設計走。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_rv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="haha" />
<ProgressBar
style="@android:style/Widget.ProgressBar.Horizontal"
android:id="@+id/pb_rv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
這個版面刻意做得很精簡:一列文字加一條水平進度列,就足以示範「下載中」或「掃描中」這類需要持續更新狀態的通知。實作時透過 RemoteViews 把版面塞進 Notification,再搭配 NotificationManager.notify() 更新進度;要注意狀態列空間有限,元件不宜過多,且更新頻率應控制,避免不必要的效能負擔。