Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 自訂 Notification:讓提醒長成你要的樣子

Notification 是讓應用程式在不跳出 Activity 的前提下提醒使用者的一種機制,也是行動裝置上最順手的 UI 形式——手機幾乎不離身,App 多半在背景執行,一旦有需要注意的事件,能即時通知就顯得格外重要。

NotificationManager 現有的能力

  • 在狀態列產生一個圖示。
  • 在展開的狀態列視窗中顯示額外資訊,並可綁定一個 Intent。
  • 閃燈或點亮 LED。
  • 觸發手機震動。
  • 發出可聽見的警示音(鈴聲或自帶音效檔)。

這些都由 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() 更新進度;要注意狀態列空間有限,元件不宜過多,且更新頻率應控制,避免不必要的效能負擔。

Copyright © Linux教程網 All Rights Reserved