Android原生Launcher3伪3D Touch分析

来源:互联网 发布:多益网络面试测试 编辑:程序博客网 时间:2024/05/22 04:25

伪3D Touch在Android7.1系统上首次推出,只有Shortcut项,在Android8.0上又增加了Notification和System Shortcut两项。由于开发需要,基于Android8.0 Launcher3代码进行分析,并有了这篇文档。如有错误之处,欢迎指出!

3D Touch

  Android的伪3D Touch效果如下图所示。3D Touch是一种立体触控技术,被苹果称为新一代多点触控技术,屏幕可感应不同的感压力度触控。为什么说Android上的是伪3D Touch呢?因为在Launcher3上的实现是通过长按屏幕触发弹出菜单的,并不是以压力传感器为触发点的。

伪3D Touch动态图

  Android实现的伪3D Touch弹出框中实现中有三种类型:System Shorcut、Shortcut、notification,分别如下图所示。System Shortcut包含小部件和应用信息两项;Shortcut则是应用深度定制的快捷方式,可以拖动到桌面;Notification则是通知栏上的通知,可以在弹出框上左右滑动直接删除Notification。当有Notification时,Shortcut最多显示两项,没有Notification时,最多显示4项。

伪3D Touch弹出框

代码实现分析

  Android的伪3D Touch功能的实现是嵌入到原来的桌面拖拽框架中的,由长按应用图标触发启动,桌面(Workspace)长按事件的处理入口放在了Launcher类中,抽屉长按事件的处理入口则在AllAppsContainerView类中,文件夹则在Folder类中。长按应用图标的处理都会调用到Workspace.beginDragShared()函数来启动拖拽流程,故这里只分析从Workspace长按应用图标的实现,另外的两种启动类似,其启动流程时序图如下所示。
伪3D Touch启动流程

  下面从长按事件回调开始详细描述代码实现。当长按的View是应用图标时会执行下面所写Launcher类的代码块,调用Workspace类的startDrag()方法,其中CellInfo记录了应用图标对应的App包括图标位置、包名、等信息,DragOptions是新增加的控制类,主要是用于拖拽过程中与伪3D Touch功能进行交互。接着调用beginDragShared()函数,参数child即点击的应用图标view。关键代码如下:

/**com.android.launcher3.Launcher*/public boolean onLongClick(View v) {       ......       } else {           final boolean isAllAppsButton =                 !FeatureFlags.NO_ALL_APPS_ICON && isHotseatLayout(v) &&                                mDeviceProfile.inv.isAllAppsButtonRank(mHotseat.getOrderInHotseat(                                        longClickCellInfo.cellX, longClickCellInfo.cellY));                if (!(itemUnderLongClick instanceof Folder || isAllAppsButton)) {                    // User long pressed on an item                    mWorkspace.startDrag(longClickCellInfo, new DragOptions());                }            }        }        return true;    }
/**com.android.launcher3.Workspace*/public void startDrag(CellLayout.CellInfo cellInfo, DragOptions options) {        View child = cellInfo.cell;        ......        beginDragShared(child, this, options);    }public void beginDragShared(View child, DragSource source, DragOptions options) {        Object dragObject = child.getTag();        if (!(dragObject instanceof ItemInfo)) {            String msg = "Drag started with a view that has no tag set. This "                    + "will cause a crash (issue 11627249) down the line. "                    + "View: " + child + "  tag: " + child.getTag();            throw new IllegalStateException(msg);        }        beginDragShared(child, source, (ItemInfo) dragObject,                new DragPreviewProvider(child), options);    }

  在Workspace的beginDragShared()函数中会调用PopupContainerWithArrow.showForIcon()函数,伪3D Touch的弹出框会在这里添加进来,如果不可以显示弹出框,该函数将会返回null,否则会返回对象popupContainer 。当popupContainer不为空说明需要显示弹出框,这时会调用createPreDragCondition()函数创建DragOptions.PreDragCondition对象赋值给dragOptions.preDragCondition。DragOptions.PreDragCondition接口有三个函数:shouldStartDrag()通过移动的距离判断是否可以开始真正的拖拽流程;当弹出框开始显示时会调用onPreDragStart();结束时会调用onPreDragEnd()。之后调用的DragController.startDrag(),当有弹出框显示时,这里只是做拖拽前的准备工作,并不是真正的开始拖拽。关键代码如下:

/**com.android.launcher3.Workspace*/public DragView beginDragShared(View child, DragSource source, ItemInfo dragObject,            DragPreviewProvider previewProvider, DragOptions dragOptions) {        ......        if (child instanceof BubbleTextView && !dragOptions.isAccessibleDrag) {            PopupContainerWithArrow popupContainer = PopupContainerWithArrow                    .showForIcon((BubbleTextView) child);            if (popupContainer != null) {                dragOptions.preDragCondition = popupContainer.createPreDragCondition();                mLauncher.getUserEventDispatcher().resetElapsedContainerMillis();            }        }        DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source,                dragObject, dragVisualizeOffset, dragRect, scale, dragOptions);        dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());        b.recycle();        return dv;    }
public interface PreDragCondition {        public boolean shouldStartDrag(double distanceDragged);        /**         * The pre-drag has started, but onDragStart() is         * deferred until shouldStartDrag() returns true.         */        void onPreDragStart(DropTarget.DragObject dragObject);        /**         * The pre-drag has ended. This gets called at the same time as onDragStart()         * if the condition is met, otherwise at the same time as onDragEnd().         * @param dragStarted Whether the pre-drag ended because the actual drag started.         *                    This will be true if the condition was met, otherwise false.         */        void onPreDragEnd(DropTarget.DragObject dragObject, boolean dragStarted);    }

  回到PopupContainerWithArrow.shortForIcon()函数,这里调用PopupDataProvider.getShortcutIdsForItem()函数来获取Shortcut项、调用PopupDataProvider.getNotificationKeysForItem()函数来获取Notification项、调用 PopupDataProvider.getEnabledSystemShortcutsForItem()函数来获取System Shortcut项。获得需要显示的Item后,初始化容器container,并设为INVISIBLE,添加到DragLayer中,等视同添加完毕后再显示。接下来调用populateAndShow()方法把各项添加到容器View中。关键代码如下:

/**com.anroid.launcher3.popup.PopupContainerWithArrow*//*** Shows the notifications and deep shortcuts associated with {@param icon}.* @return the container if shown or null.*/public static PopupContainerWithArrow showForIcon(BubbleTextView icon) {        ......        PopupDataProvider popupDataProvider = launcher.getPopupDataProvider();        List<String> shortcutIds = popupDataProvider.getShortcutIdsForItem(itemInfo);        List<NotificationKeyData> notificationKeys = popupDataProvider                .getNotificationKeysForItem(itemInfo);        List<SystemShortcut> systemShortcuts = popupDataProvider                .getEnabledSystemShortcutsForItem(itemInfo);        final PopupContainerWithArrow container =                (PopupContainerWithArrow) launcher.getLayoutInflater().inflate(                        R.layout.popup_container, launcher.getDragLayer(), false);        container.setVisibility(View.INVISIBLE);        launcher.getDragLayer().addView(container);        container.populateAndShow(icon, shortcutIds, notificationKeys, systemShortcuts);        return container;    }

  在函数populateAndShow()中,首先把各项通过addDummyViews()函数添加到container中,这里添加的view并不是最后实际所显示的,而是一个虚假的视图。然后调用addArrowView()给弹出框添加箭头, animateOpen()动画显示弹出框,通过addDragListener()添加container对拖动状态的监听。函数最后的代码可以看到创建了一个绑定了工作线程的Handler,调用postAtFrontOfQueue() post一个Runable到工作线程,且放到队列前端,这个Runable就是用来获取弹出框各项如图标、title等具体信息的。通过PopupPopulator.createUpdateRunnable()创建该Runable,其中主要的参数uiHandler用于获得数据后通知视图更新,具体实现这里不再赘述,有兴趣的童鞋可自行查看。至此,伪3D Touch功能弹出框显示完成。关键代码如下:

public void populateAndShow(final BubbleTextView originalIcon, final List<String> shortcutIds,            final List<NotificationKeyData> notificationKeys, List<SystemShortcut> systemShortcuts) {        ......        // Add dummy views first, and populate with real info when ready.        PopupPopulator.Item[] itemsToPopulate = PopupPopulator                .getItemsToPopulate(shortcutIds, notificationKeys, systemShortcuts);        addDummyViews(itemsToPopulate, notificationKeys.size() > 1);        measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);        orientAboutIcon(originalIcon, arrowHeight + arrowVerticalOffset);        boolean reverseOrder = mIsAboveIcon;        if (reverseOrder) {            removeAllViews();            mNotificationItemView = null;            mShortcutsItemView = null;            itemsToPopulate = PopupPopulator.reverseItems(itemsToPopulate);            addDummyViews(itemsToPopulate, notificationKeys.size() > 1);            measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);            orientAboutIcon(originalIcon, arrowHeight + arrowVerticalOffset);        }        ......        // Add the arrow.        final int arrowHorizontalOffset = resources.getDimensionPixelSize(isAlignedWithStart() ?                R.dimen.popup_arrow_horizontal_offset_start :                R.dimen.popup_arrow_horizontal_offset_end);        mArrow = addArrowView(arrowHorizontalOffset, arrowVerticalOffset, arrowWidth, arrowHeight);        mArrow.setPivotX(arrowWidth / 2);        mArrow.setPivotY(mIsAboveIcon ? 0 : arrowHeight);        animateOpen();        mLauncher.getDragController().addDragListener(this);        mOriginalIcon.forceHideBadge(true);        // Load the shortcuts on a background thread and update the container as it animates.        final Looper workerLooper = LauncherModel.getWorkerLooper();        new Handler(workerLooper).postAtFrontOfQueue(PopupPopulator.createUpdateRunnable(                mLauncher, originalItemInfo, new Handler(Looper.getMainLooper()),                this, shortcutIds, shortcutViews, notificationKeys, mNotificationItemView,                systemShortcuts, systemShortcutViews));    }

  当显示完弹出框,用户继续拖动图标时,MotionEvent.ACTION_MOVE事件的处理最终会交到DragController.handleMoveEvent()。函数里会调用DragCondition.shouldStartDrag()判断拖动的距离决定是否开始拖拽流程。当拖动的距离大于设定的距离时调用callOnDragStart()函数开始真正的拖拽。回调所有DragListener的onDragStart函数,包括PopupContainerWithArrow的onDragStart(),该函数中调用animateClose()移除弹出框。关键代码如下:

private void handleMoveEvent(int x, int y) {        mDragObject.dragView.move(x, y);        ······        if (mIsInPreDrag && mOptions.preDragCondition != null                && mOptions.preDragCondition.shouldStartDrag(mDistanceSinceScroll)) {            callOnDragStart();        }    }private void callOnDragStart() {        for (DragListener listener : new ArrayList<>(mListeners)) {            listener.onDragStart(mDragObject, mOptions);        }        if (mOptions.preDragCondition != null) {            mOptions.preDragCondition.onPreDragEnd(mDragObject, true /* dragStarted*/);        }        mIsInPreDrag = false;    }

最后

  Android的伪3D Touch功能提供了深度定制快捷方式,快速查看、处理notification,快速查看应用信息,添加小部件的入口。Shortcut项需要应用进行定制,且需要把Launcher设为默认桌面一次后才能读取、显示。而Notification项则需要打开获取通知权限才能读取、显示。

原创粉丝点击