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

Android Notification 通知提醒實作詳解:從常駐通知到自訂樣式

編輯:關於 Android 程式設計

需要跟使用者溝通「一件重要但不急著看的事」時,Toast 並不合適——它兩秒就消失,無法回看。這正是 Notification 的價值所在:它會常駐在狀態欄,使用者下拉即可查看,離開 App 也不受影響。本文以實例說明三種常見做法:常駐型通知、系統預設提醒效果,以及完全自訂視圖的個性化通知。

一、準備工作:版面與自訂通知樣式

主介面放兩個按鈕,分別觸發一般通知與自訂通知。

<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:background="@android:color/black"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/title"
        android:textColor="#0f0"
        android:textSize="20sp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:layout_marginTop="30dp"
        android:onClick="normal"
        android:text="@string/notification"
        android:textColor="#0f0"
        android:textSize="20sp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:layout_marginTop="30dp"
        android:onClick="custom"
        android:text="@string/custom"
        android:textColor="#0f0"
        android:textSize="20sp" />
</LinearLayout>

自訂通知的內容視圖則獨立成一個布局檔,這裡只放一張圖與一行文字。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:contentDescription="@string/action_settings"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textColor="#0f0"
        android:textSize="15sp" />
</LinearLayout>

二、程式碼實作

package com.itfom.notification;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.RemoteViews;

public class MainActivity extends Activity {

    private NotificationManager mNotificationManager;
    private Context context;
    private Notification notification;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // 一般通知
    @SuppressWarnings("deprecation")
    public void normal(View v) {
        createNotification("普通的通知");

        // 常駐於「正在執行」區,不輕易清除
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notification.defaults |= Notification.DEFAULT_LIGHTS;
        // 點擊後自動消失
        notification.defaults |= Notification.FLAG_AUTO_CANCEL;

        String textTitle = "Notification 示例";
        String textContent = "程式正在執行,點擊此處跳轉到演示介面";

        Intent it = new Intent(context, MainActivity.class);
        PendingIntent pendintent = PendingIntent.getActivity(context, 0, it, 0);
        notification.setLatestEventInfo(context, textTitle, textContent, pendintent);

        mNotificationManager.notify(0, notification);
    }

    // 自訂通知
    public void custom(View v) {
        createNotification("個性化的通知");

        // 自訂提示音(放在 SD 卡根目錄的 non.mp3)
        notification.sound = Uri.parse(Environment.getExternalStorageDirectory() + "/non.mp3");

        // 自訂震動節奏:立即震 0ms、停 100ms、震 200ms、停 300ms
        long[] vibrate = {0, 100, 200, 300};
        notification.vibrate = vibrate;

        // 自訂 LED 呼吸燈顏色與頻率
        notification.ledARGB = 0xff00ff00;
        notification.ledOnMS = 500;
        notification.ledOffMS = 500;
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;

        RemoteViews contentView = new RemoteViews(this.getPackageName(), R.layout.notify);
        contentView.setTextViewText(R.id.tv, "這是個性化的通知");
        notification.contentView = contentView;

        Intent it = new Intent(context, MainActivity.class);
        PendingIntent pendintent = PendingIntent.getActivity(context, 0, it, 0);
        notification.contentIntent = pendintent;

        mNotificationManager.notify(1, notification);
    }

    // 一般通知與自訂通知的前段建立流程相同,因此抽成獨立方法
    @SuppressWarnings("deprecation")
    public Notification createNotification(String text) {
        context = this;
        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        return notification = new Notification(icon, text, when);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        // 離開時一併取消通知
        mNotificationManager.cancel(0);
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }
}

按下兩個按鈕後的效果如下。一般通知走系統預設的聲音、震動與燈光;自訂通知則使用自備音效、三段震動節奏與綠色呼吸燈。

註:截圖無法呈現聲音,實際執行時會有提示音;若裝置有補光燈,也能看到 LED 閃爍。

三、三個實務提醒

其一,createNotification() 之所以獨立出來,是因為不論一般或自訂通知,開頭的取得服務與建立物件流程都一樣,抽出來可避免重複。其二,自訂視圖必須透過 RemoteViews 而非一般 View,因為通知實際上是跨進程繪製的。其三,上述寫法使用了 setLatestEventInfo() 與 new Notification() 這類已被標記為老舊的 API,新專案請改用 Notification.Builder 或 NotificationCompat.Builder,並記得在 Android 8.0 以上建立 NotificationChannel,同時處理通知執行權限的申請。

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