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

Android 通知機制完整教學:從基本發送到 PendingIntent 點擊與音效震動

編輯:關於 Android 程式設計

通知(Notification)是 Android 相當有特色的一項設計。當應用程式想提醒使用者某件事,而自己又不在前景執行時,通知就是最合適的管道:發出後,手機最上方的狀態欄會出現一個小圖示,下拉即可看到完整內容。

一、基本用法:四個步驟

不論是在 Activity、BroadcastReceiver 還是 Service 中建立通知,流程都一樣。

1. 取得 NotificationManager

NotificationManager manager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

getSystemService() 接受一個字串參數決定要取哪個系統服務,這裡傳入 Context.NOTIFICATION_SERVICE。

2. 建立 Notification 物件

Notification notification = new Notification(
        R.drawable.ic_launcher,          // 狀態欄小圖示
        "this is ticker text",           // 通知出現時短暫閃過的文字
        System.currentTimeMillis());    // 通知時間,毫秒

3. 設定通知的標準佈局

notification.setLatestEventInfo(this,
        "this is content title",         // 標題
        "this is content text",          // 內文
        null);                           // PendingIntent,先留空

4. 發出通知

manager.notify(1, notification);

第一個參數是 id,每個通知的 id 都必須不同;第二個參數就是剛剛建立好的 Notification 物件。

二、動手做一個 NotificationTest

建立專案後,先在 activity_main.xml 放一顆按鈕:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/send_notice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="send notice" />
</LinearLayout>

接著在 MainActivity 中掛上點擊事件:

public class MainActivity extends Activity implements OnClickListener {

    private Button sendNotice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendNotice = (Button) findViewById(R.id.send_notice);
        sendNotice.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_notice:
                NotificationManager manager = (NotificationManager)
                        getSystemService(Context.NOTIFICATION_SERVICE);
                Notification notification = new Notification(
                        R.drawable.ic_launcher,
                        "this is ticker text",
                        System.currentTimeMillis());
                notification.setLatestEventInfo(this,
                        "this is content title",
                        "this is content text", null);
                manager.notify(1, notification);
                break;
            default:
                break;
        }
    }
}

執行程式、按下按鈕,通知就送出了。

下拉系統狀態欄,可以看到剛才設定的標題與內容:

三、加上點擊效果:PendingIntent 登場

上面這條通知是點不動的。想讓使用者點擊後跳轉頁面,就得靠 PendingIntent。

PendingIntent 與 Intent 相當類似,兩者都能描述一個「意圖」,都能用來啟動 Activity、啟動 Service 或送出廣播。差別在於:Intent 傾向立刻執行,PendingIntent 則傾向在「某個恰當的時機」由別人代為執行。你可以把它理解成延遲執行的 Intent,同時附带一份執行權限授權。

它提供 getActivity()、getBroadcast()、getService() 三個靜態方法取得實例,參數結構相同:

  • 第一個參數:Context。
  • 第二個參數:requestCode,一般傳 0。
  • 第三個參數:Intent 物件,用來描述要執行的動作。
  • 第四個參數:行為旗標,可選 FLAG_ONE_SHOT、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT、FLAG_UPDATE_CURRENT。

還記得 setLatestEventInfo() 那個被我們傳入 null 的第四個參數嗎?它正是 PendingIntent。把它填進去,通知就能點了。

準備要跳轉的目標頁面

新增 notification_layout.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="this is notification layout" />
</LinearLayout>

新增 NotificationActivity 並記得在 AndroidManifest.xml 註冊:

public class NotificationActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notification_layout);
    }
}

把 PendingIntent 接上

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.send_notice:
            NotificationManager manager = (NotificationManager)
                    getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notification = new Notification(
                    R.drawable.ic_launcher,
                    "this is ticker text",
                    System.currentTimeMillis());

            Intent intent = new Intent(this, NotificationActivity.class);
            PendingIntent pi = PendingIntent.getActivity(
                    this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

            notification.setLatestEventInfo(this,
                    "this is content title",
                    "this is content text", pi);
            manager.notify(1, notification);
            break;
        default:
            break;
    }
}

重新執行,按下按鈕發出通知,下拉狀態欄點擊該通知,就會跳到 NotificationActivity。

順手把通知收掉

你會發現跳轉後狀態欄的圖示還在。這是因為若沒有主動取消,通知會一直留著。在目標頁面呼叫 cancel() 即可:

public class NotificationActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notification_layout);
        NotificationManager manager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(1);   // 1 就是發通知時指定的 id
    }
}

四、進階技巧:聲音、震動與呼吸燈

觀察 Notification 這個類別,你會發現還有不少屬性沒派上用場。

播放提示音

Uri soundUri = Uri.parse(
        new File("/system/media/audio/ringtones/basic_tone.ogg").toString());
notification.sound = soundUri;

sound 是 Uri 型別,所以要先取得音檔的 URI。

手機震動

long[] vibrates = {0, 1000, 1000, 1000};
notification.vibrate = vibrates;

這是一組長整數陣列,以毫秒為單位交替表示靜止與震動:索引 0 是靜止時長,索引 1 是震動時長,索引 2 又是靜止,依此類推。上例即「立刻震動 1 秒、靜止 1 秒、再震動 1 秒」。

使用震動需要在 AndroidManifest.xml 中宣告權限:

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

控制 LED 呼吸燈

多數手機配備狀態燈,未接來電或未讀訊息且螢幕鎖定時會閃爍提醒。相關屬性有四個:

notification.ledARGB = Color.GREEN;              // 燈色,紅綠藍三選
notification.ledOnMS = 1000;                     // 亮起的持續時間
notification.ledOffMS = 1000;                    // 熄滅的持續時間
notification.flags = Notification.FLAG_SHOW_LIGHTS;  // 啟用發光行為

偷懶做法:直接用系統預設

懶得逐一設定時,可以讓系統依當前環境自行決定鈴聲與震動:

notification.defaults = Notification.DEFAULT_ALL;

要留意的是,這些進階效果必須在真機上才能驗證,模擬器無法呈現震動與 LED 閃爍。

五、實務提醒

本文示範的 setLatestEventInfo() 寫法在 Android 5.0 之後已被移除,新專案請改用 NotificationCompat.Builder,並透過 NotificationManagerCompat.notify() 發送,才能同時兼顧各版本的相容性。此外,Android 8.0 起還必須先建立 NotificationChannel,否則通知不會顯示。觀念是相通的:Builder 組裝內容、PendingIntent 決定點擊行為、Manager 負責送出與取消。

通知的部分就整理到這裡,下一篇再來談簡訊的接收與發送。

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