源碼角度分析Android Q新特性 Bubble

介紹

Bubbles(氣泡)是Android Q中的一項新功能,借助氣泡,用戶可以輕松地在設(shè)備上的任何位置進行多任務(wù)處理。

更多官方描述請參考:氣泡 | Android 開發(fā)者 。

發(fā)送通知

按正常的Notification的流程,從NotificationManager到NotificationManagerService不過多介紹,直接從NotificationManagerService開始。

    /**
     * Updates the flags for this notification to reflect whether it is a bubble or not.
     */
    private void flagNotificationForBubbles(NotificationRecord r, String pkg, int userId,
            NotificationRecord oldRecord) {
        Notification notification = r.getNotification();
        if (isNotificationAppropriateToBubble(r, pkg, userId, oldRecord)) {
            notification.flags |= FLAG_BUBBLE;
        } else {
            notification.flags &= ~FLAG_BUBBLE;
        }
    }

    /**
     * @return whether the provided notification record is allowed to be represented as a bubble.
     */
    private boolean isNotificationAppropriateToBubble(NotificationRecord r, String pkg, int userId,
            NotificationRecord oldRecord) {
        Notification notification = r.getNotification();
        Notification.BubbleMetadata metadata = notification.getBubbleMetadata();
        boolean intentCanBubble = metadata != null
                && canLaunchInActivityView(getContext(), metadata.getIntent(), pkg);

        // Does the app want to bubble & is able to bubble
        boolean canBubble = intentCanBubble
                && mPreferencesHelper.areBubblesAllowed(pkg, userId)
                && mPreferencesHelper.bubblesEnabled(r.sbn.getUser())
                && r.getChannel().canBubble()
                && !mActivityManager.isLowRamDevice();

        // Is the app in the foreground?
        final boolean appIsForeground =
                mActivityManager.getPackageImportance(pkg) == IMPORTANCE_FOREGROUND;

        // Is the notification something we'd allow to bubble?
        // A call with a foreground service + person
        ArrayList<Person> peopleList = notification.extras != null
                ? notification.extras.getParcelableArrayList(Notification.EXTRA_PEOPLE_LIST)
                : null;
        boolean isForegroundCall = CATEGORY_CALL.equals(notification.category)
                && (notification.flags & FLAG_FOREGROUND_SERVICE) != 0;
        // OR message style (which always has a person) with any remote input
        Class<? extends Notification.Style> style = notification.getNotificationStyle();
        boolean isMessageStyle = Notification.MessagingStyle.class.equals(style);
        boolean notificationAppropriateToBubble =
                (isMessageStyle && hasValidRemoteInput(notification))
                || (peopleList != null && !peopleList.isEmpty() && isForegroundCall);

        // OR something that was previously a bubble & still exists
        boolean bubbleUpdate = oldRecord != null
                && (oldRecord.getNotification().flags & FLAG_BUBBLE) != 0;
        return canBubble && (notificationAppropriateToBubble || appIsForeground || bubbleUpdate);
    }

    /**
     * Whether an intent is properly configured to display in an {@link android.app.ActivityView}.
     *
     * @param context       the context to use.
     * @param pendingIntent the pending intent of the bubble.
     * @param packageName   the notification package name for this bubble.
     */
    // Keep checks in sync with BubbleController#canLaunchInActivityView.
    @VisibleForTesting
    protected boolean canLaunchInActivityView(Context context, PendingIntent pendingIntent,
            String packageName) {
        if (pendingIntent == null) {
            Log.w(TAG, "Unable to create bubble -- no intent");
            return false;
        }

        // Need escalated privileges to get the intent.
        final long token = Binder.clearCallingIdentity();
        Intent intent;
        try {
            intent = pendingIntent.getIntent();
        } finally {
            Binder.restoreCallingIdentity(token);
        }

        ActivityInfo info = intent != null
                ? intent.resolveActivityInfo(context.getPackageManager(), 0)
                : null;
        if (info == null) {
            StatsLog.write(StatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED, packageName,
                    BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_MISSING);
            Log.w(TAG, "Unable to send as bubble -- couldn't find activity info for intent: "
                    + intent);
            return false;
        }
        if (!ActivityInfo.isResizeableMode(info.resizeMode)) {
            StatsLog.write(StatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED, packageName,
                    BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__ACTIVITY_INFO_NOT_RESIZABLE);
            Log.w(TAG, "Unable to send as bubble -- activity is not resizable for intent: "
                    + intent);
            return false;
        }
        if (info.documentLaunchMode != DOCUMENT_LAUNCH_ALWAYS) {
            StatsLog.write(StatsLog.BUBBLE_DEVELOPER_ERROR_REPORTED, packageName,
                    BUBBLE_DEVELOPER_ERROR_REPORTED__ERROR__DOCUMENT_LAUNCH_NOT_ALWAYS);
            Log.w(TAG, "Unable to send as bubble -- activity is not documentLaunchMode=always "
                    + "for intent: " + intent);
            return false;
        }
        if ((info.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) {
            Log.w(TAG, "Unable to send as bubble -- activity is not embeddable for intent: "
                    + intent);
            return false;
        }
        return true;
    }

由于是新功能,所以源碼里的注釋給的挺多的樣子,判斷一條通知是不是需要以Bubble的形式顯示,所有條件都在上面的方法里說明了:

  • 必須設(shè)定有效的BubbleMetadata。
  • BubbleMetadata中的PendingIntent必須是有效Activity,Activity必須設(shè)置resizeableActivity,documentLaunchMode,allowEmbedded等屬性。
  • 必須允許bubble功能(這點官方文檔中已經(jīng)說明,該功能必須在開發(fā)者選項中手動啟用,啟用后應(yīng)用默認允許bubble,可在通知設(shè)置中關(guān)閉)。
  • 以下三項滿足一項或多項即可:
    1.通知使用了MessagingStyle,并且設(shè)定了有效的action(官方文檔中的描述是添加了Person對象?);
    2.通知為前臺服務(wù)FLAG_FOREGROUND_SERVICE,類別為CATEGORY_CALL,并且添加了Person對象;
    3.發(fā)送通知時該應(yīng)用在前臺運行。

如果判斷成立,給通知加上FLAG_BUBBLE標記。

處理通知

frameworks → SystemUI 流程:
(frameworks) NotificationManager → NotificationManagerService → NotificationListenerService → (SystemUI) NotificationListener → NotificationEntryManager → BubbleController

Notification inflate view流程:
NotificationEntryManager.addNotificationInternal(...) → NotificationRowBinderImpl.inflateViews(...) →
SystemUI中有個類BubbleController,是用來處理bubble添加、刪除以及在屏幕上顯示狀態(tài)等事件的。

BubbleController里面注冊一些listeners,其中包括監(jiān)聽notification entry相關(guān)事件的listener,當有通知需要被添加進來時會回調(diào)對應(yīng)的方法。

    private final NotificationEntryListener mEntryListener = new NotificationEntryListener() {
        @Override
        public void onPendingEntryAdded(NotificationEntry entry) {
            // 判斷當前系統(tǒng)設(shè)置是否允許bubbles
            if (!areBubblesEnabled(mContext)) {
                return;
            }
            // 判斷該entry是否能夠以bubble狀態(tài)顯示,包括:應(yīng)用是否允許bubbles,通知是否含有FLAG_BUBBLE標記,metadata是否有效等,
            // 以及不被DND(勿擾)、snooze(打盹)、VR mode等設(shè)置覆蓋.
            if (mNotificationInterruptionStateProvider.shouldBubbleUp(entry)
                    // 看方法名就知道與NMS里的基本一致,在這邊再判斷一遍
                    && canLaunchInActivityView(mContext, entry)) {
                // 是否允許bubble與通知欄里的通知同時存在
                updateShowInShadeForSuppressNotification(entry);
            }
        }
        ...
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容