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

介绍

Bubbles(气泡)是Android Q中的一项新功能,借助气泡,用户可以轻松地在设备上的任何位置进行多任务处理。

更多官方描述请参考:气泡 | Android 开发者 。

发送通知

按正常的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 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 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的形式显示,所有条件都在上面的方法里说明了:

  • 必须设定有效的BubbleMetadata。
  • BubbleMetadata中的PendingIntent必须是有效Activity,Activity必须设置resizeableActivity,documentLaunchMode,allowEmbedded等属性。
  • 必须允许bubble功能(这点官方文档中已经说明,该功能必须在开发者选项中手动启用,启用后应用默认允许bubble,可在通知设置中关闭)。
  • 以下三项满足一项或多项即可:
    1.通知使用了MessagingStyle,并且设定了有效的action(官方文档中的描述是添加了Person对象?);
    2.通知为前台服务FLAG_FOREGROUND_SERVICE,类别为CATEGORY_CALL,并且添加了Person对象;
    3.发送通知时该应用在前台运行。

如果判断成立,给通知加上FLAG_BUBBLE标记。

处理通知

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

Notification inflate view流程:
NotificationEntryManager.addNotificationInternal(...) → NotificationRowBinderImpl.inflateViews(...) →
SystemUI中有个类BubbleController,是用来处理bubble添加、删除以及在屏幕上显示状态等事件的。

BubbleController里面注册一些listeners,其中包括监听notification entry相关事件的listener,当有通知需要被添加进来时会回调对应的方法。

    private final NotificationEntryListener mEntryListener = new NotificationEntryListener() {
        @Override
        public void onPendingEntryAdded(NotificationEntry entry) {
            // 判断当前系统设置是否允许bubbles
            if (!areBubblesEnabled(mContext)) {
                return;
            }
            // 判断该entry是否能够以bubble状态显示,包括:应用是否允许bubbles,通知是否含有FLAG_BUBBLE标记,metadata是否有效等,
            // 以及不被DND(勿扰)、snooze(打盹)、VR mode等设置覆盖.
            if (mNotificationInterruptionStateProvider.shouldBubbleUp(entry)
                    // 看方法名就知道与NMS里的基本一致,在这边再判断一遍
                    && canLaunchInActivityView(mContext, entry)) {
                // 是否允许bubble与通知栏里的通知同时存在
                updateShowInShadeForSuppressNotification(entry);
            }
        }
        ...
    }

你可能感兴趣的:(源码角度分析Android Q新特性 Bubble)