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

Android Notification 通知機制解析與完整範例

編輯:關於 Android 程式設計

Notification 是顯示在手機狀態欄的通知,屬於系統層級的全域提示,通常由 NotificationManager 統一管理。不論訊息來自聊天軟體還是下載進度,使用者看到的都是同一套機制。本文拆解它的四個步驟,並用一個可運行的範例串起來。

使用 Notification 的四個步驟

  • 呼叫 getSystemService(NOTIFICATION_SERVICE) 取得 NotificationManager,負責發送與回收通知
  • 建立 Notification 物件
  • 為它設定各種屬性,最後呼叫 build 產生物件
  • 透過 NotificationManager 發送

一、取得系統服務

private NotificationManager nm;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // 取得系統的通知管理器
    nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

二、發送通知

為主布局的兩個按鈕加上監聽事件,一個負責發送、一個負責取消。屬性設定都在程式碼中註明了用途,細節可再對照 API 文件。

public void send(View view) {

    // 點擊通知後要開啟的 Activity
    Intent intent = new Intent(MainActivity.this, OtherActivity.class);
    // PendingIntent 負責延遲啟動
    PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);

    Notification notify = new Notification.Builder(this)
            .setAutoCancel(true)                    // 點擊後通知自動消失
            .setTicker("新消息")                     // 狀態欄提示文字
            .setSmallIcon(R.mipmap.ic_launcher)     // 狀態欄圖示
            .setContentTitle("一條新通知")            // 通知標題
            .setContentText("恭喜你通知欄測試成功")     // 通知內容
            // 使用系統預設聲音與呼吸燈;若要全部預設效果可改為 DEFAULT_ALL
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS)
            // 也可自訂音效:setSound(Uri.parse(...))
            .setContentIntent(pi)
            .build();

    // 透過 NotificationManager 發送,1 為通知 id
    nm.notify(1, notify);
}

這裡的 OtherActivity 就是點擊通知後要開啟的頁面,必須在清單檔中註冊。另外,由於用到了閃光燈與震動器,也要補上對應權限:

<activity android:name=".OtherActivity"></activity>

<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-permission android:name="android.permission.VIBRATE"/>

三、取消通知

// 取消通知
public void closed(View view) {
    nm.cancel(1);
}

取消的方式就是呼叫 cancel(id),id 必須與發送時一致,否則找不到對應的通知。

四、主介面布局

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:orientation="horizontal"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="開啟通知"
        android:onClick="send"
        android:id="@+id/btnstartnotification" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="關閉通知"
        android:onClick="closed"
        android:id="@+id/btnstopnotification" />
</LinearLayout>

整體用起來相當輕量。若要在新專案中使用,請留意兩件事:Notification.Builder 建議替換為 NotificationCompat.Builder 以取得相容性,且 Android 8.0 起必須先建立 NotificationChannel,否則通知不會顯示;Android 13 以上還需要 POST_NOTIFICATIONS 執行權限。

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