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

Android 通知進階用法與源碼解析:動態更新、大視圖、浮動通知與圖示角標

編輯:關於 Android 開發

用 Android 手機這麼久、裝過這麼多 App,遇過不少有意思的通知樣式。這篇先把兩類比較特殊的做法整理出來:Notification 的變體玩法,以及桌面圖示上的數字角標。文中會穿插一些源碼分析,幫助理解為什麼某些寫法在特定版本會失效。

一、動態變更的通知

把 setOngoing(true) 設定上去之後,通知會一直停留在通知欄,直到被 cancel 或應用退出。這正是計時器、音樂播放、下載進度這類場景需要的形態——通知一直在,但內容要隨時間更新。

下面以每秒刷新一次的計時器為例:

private Timer timer;
private TimerTask task;

if (timer != null) return;
timer = new Timer("time");
task = new TimerTask() {
    @Override
    public void run() {
        showDynamicNotification();
    }
};
timer.scheduleAtFixedRate(task, 0, 1000);

private void showDynamicNotification() {
    mBuilder = new NotificationCompat.Builder(NotificationActivity.this);

    RemoteViews view = new RemoteViews(getPackageName(), R.layout.layout_notification);
    view.setTextViewText(R.id.tv_number, parseDate());
    view.setImageViewResource(R.id.iv_icon, R.mipmap.ic_launcher);

    Intent intent = new Intent(NOTIFY_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            NotificationActivity.this, 1000, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent)
            .setTicker("you got a new message")
            .setOngoing(true)
            .setContent(view);

    notification = mBuilder.build();
    notificationManager.notify(NOTIFY_ID2, notification);
}

private String parseDate() {
    SimpleDateFormat format = new SimpleDateFormat("yyyy hh:mm:ss", Locale.getDefault());
    return format.format(System.currentTimeMillis());
}

幾個容易踩到的重點:

Notification.Builder 是 API 11 才引入的,為了向下相容,實務上通常用 support-v4 提供的 NotificationCompat.Builder 來建構。

動態更新的關鍵在 notify() 的 id 參數。這個 id 在應用內必須唯一——如果不唯一,在部分 4.x 機型上會出現 PendingIntent 無法回呼的怪現象(我在紅米上就遇過)。更新某個通知的做法是:用相同的 id 再 notify 一次。若舊通知仍在顯示,系統會依新物件內容更新它;若舊通知已被清掉,系統則會建立一條新的。

PendingIntent 的四個 flag 值得記一下:

FLAG_CANCEL_CURRENT:若已存在則取消舊的、重建新的。
FLAG_NO_CREATE:若不存在就不再建立。
FLAG_ONE_SHOT:只能使用一次。
FLAG_UPDATE_CURRENT:若已存在則替換內容,最常用。

另外,這裡用的是完全自訂的 RemoteViews,它的更新機制與普通 View 不同,有興趣的可以另外深入研究。

二、大視圖樣式(Big View)

Notification 有兩種視覺風格:標準視圖(Normal View)各版本通用;大視圖(Big View)則需要 Android 4.1 以上。郵件、音樂這類資訊量大的 App 很愛用。系統透過 setStyle() 提供三種預設樣式:

NotificationCompat.BigPictureStyle:在展開區顯示一張大圖(約 256dp 高)。
NotificationCompat.BigTextStyle:顯示一大段文字。
NotificationCompat.InboxStyle:顯示多行清單式文字。

API 21 之後又多了一個 Notification.MediaStyle,做出來的效果跟主流音樂播放器的通知介面幾乎一樣:

不想用預設樣式,也可以完全自訂版面。例如下面這種:

以下用一個簡易實作說明,效果如下:

RemoteViews smallView = new RemoteViews(getPackageName(), R.layout.layout_notification);
smallView.setTextViewText(R.id.tv_number, parseDate());
smallView.setImageViewResource(R.id.iv_icon, R.mipmap.ic_launcher);

mBuilder = new NotificationCompat.Builder(NotificationActivity.this);
mBuilder.setSmallIcon(R.mipmap.ic_launcher)
        .setNumber((int) (Math.random() * 1000))  // API 21 之後狀態欄不再顯示數字
        .setTicker("you got a new message")
        .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
        .setAutoCancel(true)
        .setWhen(0)
        .setPriority(NotificationCompat.PRIORITY_LOW);

intent = new Intent(NOTIFY_ACTION);
pendingIntent = PendingIntent.getBroadcast(NotificationActivity.this, 1000,
                                           intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);

// 5.0 之後可支援在鎖屏介面顯示通知
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
}

notification = mBuilder.build();
notification.contentView = smallView;

// 系統版本 >= Android 4.1 才支援大視圖
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    RemoteViews view = new RemoteViews(getPackageName(), R.layout.layout_big_notification);
    view.setTextViewText(R.id.tv_name, "這裡放一段比較長的文字內容……");
    view.setOnClickPendingIntent(R.id.btn_click_close,
            PendingIntent.getBroadcast(NotificationActivity.this, 1001,
                    new Intent(CLICK_ACTION), PendingIntent.FLAG_UPDATE_CURRENT));
    notification.bigContentView = view;
}

notificationManager.notify(NOTIFY_ID3, notification);

對應的 XML 佈局:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:background="#ef222222"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:padding="10dp">

    <FrameLayout
        android:layout_height="150dp"
        android:layout_width="match_parent">

        <ImageView
            android:id="@+id/iv_icon"
            android:background="@mipmap/ic_launcher"
            android:layout_gravity="center_vertical"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content" />

        <LinearLayout
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_name"
                android:ellipsize="marquee"
                android:fadingedge="horizontal"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:gravity="center"
                android:layout_height="wrap_content"
                android:layout_width="fill_parent"
                android:marqueeRepeatLimit="marquee_forever"
                android:scrollHorizontally="false"
                android:singleLine="true"
                android:textColor="#fff"
                android:textSize="15sp">
                <requestFocus />
            </TextView>

            <Button
                android:id="@+id/btn_click_close"
                android:background="#ef222222"
                android:layout_gravity="center_horizontal"
                android:layout_height="40dp"
                android:layout_width="40dp"
                android:layout_marginTop="10dp"
                android:text="X"
                android:textSize="30sp" />
        </LinearLayout>
    </FrameLayout>
</LinearLayout>

幾個必須知道的版本差異

setTicker 在 API 21 之後已被標記為 Deprecated,不再有效果。
setDeleteIntent 是 API 11 新增的監聽回呼,但一旦 setAutoCancel(true),它就會失效,兩者互斥。
setPriority 用來設定通知優先級,官方文件說明得很詳細。
鎖屏顯示:API 21 起可用 setVisibility 控制。個人覺得這個特性體驗提升很明顯——簡訊這類私密通知可以設為 VISIBILITY_PRIVATE 隱藏內容,而毫無隱私的一般通知設成 VISIBILITY_PUBLIC,使用者不必解鎖就能處理。
大視圖高度:這裡有個容易困惑的點。上述 XML 中,最外層 LinearLayout 設定高度是無效的,必須多包一層 FrameLayout 並在那一層設定高度才會生效。
跑馬燈的限制:bigContentView 裡的 TextView 無法實現 marquee 效果。更麻煩的是,一旦設定了 bigContentView,連 contentView 中的 TextView marquee 也會跟著失效。這個行為相當反直覺,使用時要留意。

三、浮動通知(Heads-up)

微信那種從螢幕頂端滑出的提示,實作起來其實很簡單:

RemoteViews headsUpView = new RemoteViews(getPackageName(), R.layout.layout_heads_up_notification);

intent = new Intent(NOTIFY_ACTION);
pendingIntent = PendingIntent.getBroadcast(NotificationActivity.this, 1000,
                                          intent, PendingIntent.FLAG_UPDATE_CURRENT);

mBuilder = new NotificationCompat.Builder(NotificationActivity.this);
mBuilder.setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("this is notification title test")
        .setContentText("this is notification text test")
        .setNumber((int) (Math.random() * 1000))
        .setTicker("you got a new message")
        // 一定要設定 contentIntent,否則會 crash
        .setContentIntent(pendingIntent)
        .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
        .setAutoCancel(true)
        .setWhen(0);

notification = mBuilder.build();

if (Build.VERSION.SDK_INT >= 21) {
    notification.priority = Notification.PRIORITY_MAX;
    notification.headsUpContentView = headsUpView;
}

notificationManager.notify(NOTIFY_ID1, notification);

關鍵就兩個:優先級要給到 PRIORITY_MAX,並且在 API 21 以上設定 headsUpContentView。另外別忘了 setContentIntent,少了它會直接崩潰。

四、常見問題整理

1. 點擊通知要開啟一組 Activity 堆疊

這牽涉到 Task 與 Back Stack 的行為。有兩種特殊情況要留意:一是希望連父 Activity 一起按順序建立整個堆疊,但系統在建立之前會先清空原本的 task 堆疊,所以最後只剩下這幾個 Activity——如果你原本堆疊裡有 D 和 C,要開 A→B→C,系統會依序關掉 D 和 C 再依序開啟 A→B→C;二是讓 Activity 在一個獨立的新 task 中啟動,這會產生兩個堆疊。兩種做法官方文件都有說明,實作前先想清楚要哪一種。

2. Android 5.0 狀態欄圖示變成白色方塊

這個問題在部分國產 ROM 上已被修正(例如小米、錘子),但 HTC、三星等仍有出現,需要另外處理。

3. 在 2.3 上使用 setContent(RemoteViews) 是無效的

需要改用直接賦值的方式:

RemoteViews rvMain = new RemoteViews(context.getPackageName(), R.layout.notification_layout);
// TODO 設定 rvMain 的內容 ...

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
// TODO 其他設定 ...

Notification notification = builder.build();
if (Build.VERSION.SDK_INT <= 10) {
    notification.contentView = rvMain;
}

4. 通知的三種回呼時機

setContentIntent():使用者點擊通知時觸發。
setFullScreenIntent():通知顯示時就會被呼叫。
setDeleteIntent():使用者清除通知時觸發,包含點擊清除鈕與左右滑動刪除(後者需較高版本)。

補充一點:2.3 及以下版本無法處理自訂版面中的互動事件,所以在那些版本上別費心加自訂按鈕了。

五、源碼解析:一次 notify 到底做了什麼

以 NotificationManager.notify 為入口:

INotificationManager service = getService();
// ...
service.enqueueNotificationWithTag(pkg, mContext.getOpPackageName(), tag, id,
                                   stripped, idOut, UserHandle.myUserId());

getService() 的實作:

static public INotificationManager getService() {
    if (sService != null) {
        return sService;
    }
    IBinder b = ServiceManager.getService("notification");
    sService = INotificationManager.Stub.asInterface(b);
    return sService;
}

它透過 ServiceManager 取得名為 "notification" 的 Binder 物件,用於跨行程通訊,而這個 Binder 的實體就是 NotificationManagerService。這裡牽涉到兩個服務:StatusBarManagerService 與 NotificationManagerService,兩者都在 SystemServer.java 的 ServerThread 中被啟動並註冊:

class ServerThread extends Thread {
    public void run() {
        // ...
        StatusBarManagerService statusBar = null;
        NotificationManagerService notification = null;
        // ...
        statusBar = new StatusBarManagerService(context, wm);
        ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
        // ...
        notification = new NotificationManagerService(context, statusBar, lights);
        ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);
        // ...
    }
}

而 system_server 行程本身是 zygote 透過 fork 建立的。接著 enqueueNotificationWithTag 會呼叫 enqueueNotificationInternal,這才是核心。抽出關鍵片段來看:

void enqueueNotificationInternal(final String pkg, final String opPkg,
        final int callingUid, final int callingPid, final String tag, final int id,
        final Notification notification, int[] idOut, int incomingUserId) {
    // ...
    // 這裡會做數量限制:除了 android 套件與已註冊的 listener 之外,
    // 每個套件的 notification 數量都會被限制,用來防止 DOS 攻擊與資源洩漏。
    // ...

    // post 到工作 handler 中處理
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            synchronized (mNotificationList) {
                // === 評分 ===
                // 0. 先修正輸入參數
                notification.priority = clamp(notification.priority,
                        Notification.PRIORITY_MIN, Notification.PRIORITY_MAX);

                // 1. 初始分數:以 10 為單位分桶,範圍約 [-20..20]
                final int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER;

                // 2. 把 notification 封裝成 StatusBarNotification,
                //    再與 score 一起封裝成 NotificationRecord,
                //    接著呼叫 handleGroupedNotificationLocked 判斷能否跳過後續步驟。
                // ...

                // 3. 套用本地規則,統計 notification 的各項行為,
                //    把 NotificationRecord 加入 mNotificationList 並排序。
                //    若設定了 smallIcon,則通知所有 NotificationListener 有新通知。
                mRankingHelper.sort(mNotificationList);
                if (notification.getSmallIcon() != null) {
                    StatusBarNotification oldSbn = (old != null) ? old.sbn : null;
                    mListeners.notifyPostedLocked(n, oldSbn);
                } else {
                    // ...
                }

                // 通知 status bar 顯示該筆通知
                buzzBeepBlinkLocked(r);
            }
        }
    });
}

notifyPostedLocked 又會再 post 到工作 handler,最終透過 Binder 呼叫 NotificationListenerService——這個類很實用,可以繼承它來監聽系統通知的各種動作。

最後的 buzzBeepBlinkLocked() 負責判斷要不要發出聲音、震動與呼吸燈:

private void buzzBeepBlinkLocked(NotificationRecord record) {
    // ...
    // 這筆通知該不該發出聲音、震動、亮燈?
    // 如果不該,就直接跳過。
    // ...
    if (disableEffects == null
            && (!(record.isUpdate && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0))
            && (record.getUserId() == UserHandle.USER_ALL
                || record.getUserId() == currentUser
                || mUserProfiles.isCurrentProfile(record.getUserId()))
            && canInterrupt && mSystemReady && mAudioManager != null) {
        sendAccessibilityEvent(notification, record.sbn.getPackageName());
        // sound ... vibrate ... light ...
        if (buzz || beep || blink) {
            EventLogTags.writeNotificationAlert(record.getKey(),
                    buzz ? 1 : 0, beep ? 1 : 0, blink ? 1 : 0);
            mHandler.post(mBuzzBeepBlinked);
        }
    }
}

這裡有個值得注意的細節:FLAG_ONLY_ALERT_ONCE 就是靠這段判斷生效的——如果是更新且設定了這個 flag,就不會重複發出提示音。這也是為什麼「靜默更新通知」是可行的。

隨後 mBuzzBeepBlinked 被 post 到工作 handler,最終呼叫 mStatusBar.buzzBeepBlinked()。mStatusBar 是 StatusBarManagerInternal 物件,在 StatusBarManagerService 中初始化,所以最後落到:

public void buzzBeepBlinked() {
    if (mBar != null) {
        try {
            mBar.buzzBeepBlinked();
        } catch (RemoteException ex) {
        }
    }
}

整條鏈路串起來就是:NotificationManager → NotificationManagerService(評分、排序、記錄)→ NotificationListenerService(通知各個監聽者)→ StatusBarManagerService(負責震動、聲音、燈光)→ 狀態欄顯示。

六、桌面圖示數字角標

這原本被視為 iOS 的風格,但部分 Android 機型確實支援,例如三星與 HTC(m8t、6.0)的某些機型。小米則是特例——它會依 notification 的數量自動生成角標,不需要你做任何事。

對 HTC 與三星,一般可以發送一個自定罪廣播來設定:

public static void setBadge(Context context, int count) {
    String launcherClassName = getLauncherClassName(context);
    if (launcherClassName == null) {
        return;
    }
    Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
    intent.putExtra("badge_count", count);
    intent.putExtra("badge_count_package_name", context.getPackageName());
    intent.putExtra("badge_count_class_name", launcherClassName);
    context.sendBroadcast(intent);
}

public static String getLauncherClassName(Context context) {
    PackageManager pm = context.getPackageManager();
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
        if (pkgName.equalsIgnoreCase(context.getPackageName())) {
            return resolveInfo.activityInfo.name;
        }
    }
    return null;
}

要提醒的是,這套做法完全依賴各家廠商的私有實現,並非 Android 官方 API。原生系統上圖示角標至今沒有統一支援,因此正式專案若要用,務必做好版本與機型判斷,並準備好各家桌面(包括第三方 Launcher)的相容方案,別把它當成可靠的產品需求。

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