Android 11.0源码系列之IMSInputChannel

Posted bubbleben

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 11.0源码系列之IMSInputChannel相关的知识,希望对你有一定的参考价值。

android 11.0源码系列之IMS(四)InputChannel

本篇涉及到的主要代码:

frameworks\\base\\core\\java\\android\\view\\WindowManagerImpl.java

frameworks\\base\\core\\java\\android\\view\\WindowManagerGlobal.java

frameworks\\base\\core\\java\\android\\view\\ViewRootImpl.java

frameworks\\base\\core\\java\\android\\view\\InputChannel.java

frameworks\\base\\core\\jni\\android_view_InputChannel.cpp

frameworks\\base\\service\\core\\java\\com\\android\\server\\wm\\Session.java

frameworks\\base\\service\\core\\java\\com\\android\\server\\wm\\WindowManagerService.java

frameworks\\base\\service\\core\\java\\com\\android\\server\\wm\\WindowState.java

frameworks\\base\\services\\core\\jni\\com_android_server_input_InputManagerService.cpp

frameworks\\base\\service\\core\\java\\com\\android\\server\\input\\InputManagerService.java

frameworks\\native\\libs\\input\\InputTransport.cpp

frameworks\\native\\services\\inputflinger\\reader\\InputDispatcher.cpp

上一篇我们介绍了InputDispatcher利用InputChannelConnection将输入事件分发给应用进程的过程,本篇将基于View的创建流程带出InputChannelConnection的创建过程。

我们通常在Activity.onCreate里通过setContentView把自己的布局解析出来并添加到DecorView上, 但是此时界面并未显示出来,直到Activity.onResume才开始将DecorView添加到窗口上并真正呈现给用户,同理只有此时系统才能够开始接收用户的输入事件,所以InputChannelConnection也是在这个过程中注册和创建的;

1.1 handleResumeActivity

[-> ActivityThread.java]

    @Override
    public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
            String reason) {
        ......
        // TODO Push resumeArgs into the activity for consideration
        // 执行Activity.onResume回调
        final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
        if (r == null) {
            // We didn't actually resume the activity, so skipping any follow-up actions.
            return;
        }

        final Activity a = r.activity;

        // If the window hasn't yet been added to the window manager,
        // and this guy didn't finish itself or start another activity,
        // then go ahead and add the window.
        // Window还未添加到WindowManager,mStartedActivity默认为false
        boolean willBeVisible = !a.mStartedActivity;
        if (r.window == null && !a.mFinished && willBeVisible) {
            r.window = r.activity.getWindow();
            View decor = r.window.getDecorView();
            // DecorView目前还不可见
            decor.setVisibility(View.INVISIBLE);
            // wm指的是WindowManagerImpl,它实现了WindowManager接口,而WindowManager则继承于ViewManager[见小节1.2]
            ViewManager wm = a.getWindowManager();
            // 获取窗口属性
            WindowManager.LayoutParams l = r.window.getAttributes();
            // 将DecorView赋值给Activity.mDecor
            a.mDecor = decor;
            // 设置窗口类型
            l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
            l.softInputMode |= forwardBit;

            // mVisibleFromClient默认为true
            if (a.mVisibleFromClient) {
                // 如果窗口还未添加则通过WindowManager.addView将DecorView添加到窗口上[见1.3小节]
                if (!a.mWindowAdded) {
                    a.mWindowAdded = true;
                    wm.addView(decor, l);
                } else {
                    // The activity will get a callback for this {@link LayoutParams} change
                    // earlier. However, at that time the decor will not be set (this is set
                    // in this method), so no action will be taken. This call ensures the
                    // callback occurs with the decor set.
                    a.onWindowAttributesChanged(l);
                }
            }
        } else if (!willBeVisible) {
            if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
            // 隐藏窗口
            r.hideForNow = true;
        }
        ......
        r.nextIdle = mNewActivities;
        mNewActivities = r;
        if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
        // 添加IdleHandler等待resume完成
        Looper.myQueue().addIdleHandler(new Idler());
    }

如前面所提到的,Activity会在走完onResume之后通过WindowManager.addView将在onCreate过程中生成的DecorView添加到窗口上,调用流程如下所示,这里就不再赘述:

-->frameworks\\base\\core\\java\\android\\app\\ActivityThread.main
-->frameworks\\base\\core\\java\\android\\app\\ActivityThread.attach
-->frameworks\\base\\service\\core\\java\\com\\android\\server\\am\\ActivityManagerService.attachApplication
-->frameworks\\base\\service\\core\\java\\com\\android\\server\\am\\ActivityManagerService.attachApplicationLocked
-->frameworks\\base\\service\\core\\java\\com\\android\\server\\wm\\ActivityTaskManagerService.LocalService.attachApplication
-->frameworks\\base\\service\\core\\java\\com\\android\\server\\wm\\RootWindowContainer.attachApplication
-->frameworks\\base\\service\\core\\java\\com\\android\\server\\wm\\RootWindowContainer.startActivityForAttachedApplicationIfNeeded
-->frameworks\\base\\service\\core\\java\\com\\android\\server\\wm\\ActivityStackSuperVisor.realStartActivityLocked
-->frameworks\\base\\core\\java\\android\\app\\servertransaction\\ResumeActivityItem.execute
-->frameworks\\base\\core\\java\\android\\app\\ActivityThread.handleResumeActivity
1.2 Activity.getWindowManager

[-> Activity.java]

/** Retrieve the window manager for showing custom windows. */
public WindowManager getWindowManager() {
    // mWindowManager的赋值在attach方法中[见1.2.1小节]
    return mWindowManager;
}
1.2.1 Activity.attach

[-> Activity.java]

final void attach(Context context, ActivityThread aThread,
        Instrumentation instr, IBinder token, int ident,
        Application application, Intent intent, ActivityInfo info,
        CharSequence title, Activity parent, String id,
        NonConfigurationInstances lastNonConfigurationInstances,
        Configuration config, String referrer, IVoiceInteractor voiceInteractor,
        Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
    // 创建PhoneWindow
    mWindow = new PhoneWindow(this, window, activityConfigCallback);
    // 将Activity设置为PhoneWindow的callback
    mWindow.setCallback(this);
    // Window.setWindowManager:将WMS传递给Window,mToken代表SystemServer中的ActivityRecord.Token[见1.2.2小节]
    mWindow.setWindowManager(
        (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
        mToken, mComponent.flattenToString(),
        (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
    // 通过Window获取WindowManager
    mWindowManager = mWindow.getWindowManager();
}
1.2.2 Activity.getWindowManager

[-> Window.java]

public WindowManager getWindowManager() {
    return mWindowManager;
}

public void setWindowManager(WindowManager wm, IBinder appToken, String appName,
        boolean hardwareAccelerated) {
    mAppToken = appToken;
    mAppName = appName;
    mHardwareAccelerated = hardwareAccelerated;
    if (wm == null) {
        wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
    }
    // 将WindowManager强转为WindowManagerImpl,然后再调用其createLocalWindowManager[见1.2.3小节]
    mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
}
1.2.3 WindowManagerImpl.createLocalWindowManager

[-> WindowManagerImpl.java]

public WindowManagerImpl createLocalWindowManager(Window parentWindow) {
    // 直接创建WindowManagerImpl[见1.3小节]
    return new WindowManagerImpl(mContext, parentWindow);
}

DecorView最终是通过WindowManagerImpl.addView添加到Window中的,我们继续看下它的实现;

1.3 WindowManager.addView

[-> WindowManagerImpl.java]

private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();

public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
    applyDefaultToken(params);
    // 调用WindowManagerGlobal.addView[见1.3.1小节]
    mGlobal.addView(view, params, mContext.getDisplayNoVerify(), mParentWindow,
            mContext.getUserId());
}

WindowManagerImpl又继续调用了WindowMangerGlobal.addView方法;

1.3.1 WindowManagerGlobal.addView

[-> WindowManagerGlobal.java]

@UnsupportedAppUsage
private final ArrayList<View> mViews = new ArrayList<View>();
@UnsupportedAppUsage
private final ArrayList<ViewRootImpl> mRoots = new ArrayList<ViewRootImpl>();

public void addView(View view, ViewGroup.LayoutParams params,
        Display display, Window parentWindow, int userId) {
    ViewRootImpl root;
    View panelParentView = null;

    synchronized (mLock) {
        // WindowManagerGlobal持有所有View和ViewRootImpl的引用,不能重复创建
        int index = findViewLocked(view, false);
        if (index >= 0) {
            if (mDyingViews.contains(view)) {
                // Don't wait for MSG_DIE to make it's way through root's queue.
                mRoots.get(index).doDie();
            } else {
                throw new IllegalStateException("View " + view
                        + " has already been added to the window manager.");
            }
            // The previous removeView() had not completed executing. Now it has.
        }

        // 创建ViewRootImpl[见1.4小节]
        root = new ViewRootImpl(view.getContext(), display);
        // 设置LayoutParams
        view.setLayoutParams(wparams);
        // 将DecorView添加到mViews中
        mViews.add(view);
        // 将新创建的ViewRootImpl添加到mRoots中
        mRoots.add(root);
        // 将LayoutParams添加到mParams中
        mParams.add(wparams);

        // do this last because it fires off messages to start doing things
        try {
            // 调用ViewRootImpl.setView将DecorView添加到Window上[见1.5小节]
            root.setView(view, wparams, panelParentView, userId);
        } catch (RuntimeException e) {
            // BadTokenException or InvalidDisplayException, clean up.
            if (index >= 0) {
                removeViewLocked(index, true);
            }
            throw e;
        }
    }
}

WindowManagerGlobal作为WindowManagerServiceViewRootImpl沟通的桥梁,维护了所有的ViewRootImplView以及其对应的LayoutParams的引用,在分析ViewRootImpl.setView之前我们先来看看ViewRootImpl的创建;

1.4 ViewRootImpl的创建

[-> ViewRootImpl.java]

public ViewRootImpl(Context context, Display display) {
    // 获取Session[见1.4.1小节]
    this(context, display, WindowManagerGlobal.getWindowSession(),
            false /* useSfChoreographer */);
}

public ViewRootImpl(Context context, Display display, IWindowSession session) {
    this(context, display, session, false /* useSfChoreographer */);
}

public ViewRootImpl(Context context, Display display, IWindowSession session,
        boolean useSfChoreographer) {
    // IWindowSession类型的binder对象,从WindowManagerService获取,作为服务端供应用端调用
    mWindowSession = session;
    // IWindow类型的binder对象,会传递给WindowManagerService,作为服务端供WindowManagerService调用
    mWindow = new W(this);
    // 创建View.AttachInfo,它会保存Session,Window,ViewRootImpl等信息
    mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this,
            context);
    // 创建Choreographer
    mChoreographer = useSfChoreographer
            ? Choreographer.getSfInstance() : Choreographer.getInstance();
}

1.4.1 ViewRootImpl的创建

[-> WindowManagerGlobal.java]

public static IWindowSession getWindowSession() {
    synchronized (WindowManagerGlobal.class) {
        if (sWindowSession == null) {
            try {
                IWindowManager windowManager = getWindowManagerService();
                // 通过WindowManagerService.openSession获取IWindowSession[见1.4.2小节]
                sWindowSession = windowManager.openSession(
                        new IWindowSessionCallback.Stub() {
                            @Override
                            public void onAnimatorScaleChanged(float scale) {
                                ValueAnimator.setDurationScale(scale);
                            }
                        });
            } catch (RemoteException e) {
                throw e.rethrowFromSystemServer();
            }
        }
        return sWindowSession;
    }
}
1.4.2 WindowManagerService.openSession

[-> WindowManagerService.java]

class Session extends IWindowSession.Stub implements IBinder.DeathRecipient {
    @Override
    public IWindowSession openSession(IWindowSessionCallback callback) {
        // 创建并返回Session,可以看到Session是继承于IWindowSession.Stub的binder服务端对象
        return new Session(this, callback);
    }
}

ViewRootImpl的创建过程中会创建IWindowIWindowSession这2个binder对象,作为连接应用侧和系统进程侧WMS的纽带,实现了不同进程的跨进程调用;

1.5 ViewRootImpl.setView

[-> ViewRootImpl.java]

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView,
        int userId) {
    synchronized (this) {
        if (mView == null) {
            mView = view;
            mAdded = true;
            // 窗口是否添加成功的返回值
            int res; /* = WindowManagerImpl.ADD_OKAY; */
            // Schedule the first layout -before- adding to the window
            // manager, to make sure we do the relayout before receiving
            // any other events from the system.
            // 发起第一帧绘制的请求:通过Choreographer向DisplayEventReceiver注册vsync信号
            requestLayout();
            InputChannel inputChannel = null;
            if ((mWindowAttributes.inputFeatures
                    & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
                // 创建InputChannel
                inputChannel = new InputChannel();
            }

            try {
                // 调用Session.addToDisplayAsUser[见1.6小节]
                res = mWindowSession.addToDisplayAsUser(mWindow, mSeq, mWindowAttributes,
                        getHostVisibility(), mDisplay.getDisplayId(), userId, mTmpFrame,
                        mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                        mAttachInfo.mDisplayCutout, inputChannel,
                        mTempInsets, mTempControls);
                setFrame(mTmpFrame);
            }

            if (DEBUG_LAYOUT) Log.v(mTag, "Added window " + mWindow);

            if (inputChannel != null) {
                if (mInputQueueCallback != null) {
                    mInputQueue = new InputQueue();
                    mInputQueueCallback.onInputQueueCreated(mInputQueue);
                }
                // 通过返回的客户端InputChannel注册WindowInputEventReceiver接收输入事件
                mInputEventReceiver = new WindowInputEventReceiver(inputChannel,
                        Looper.myLooper());
            }
            // 将ViewRootImpl设置为DecorView的parent
            view.assignParent(this);

            // Set up the input pipeline.
            // 设置输入事件的处理责任链
            CharSequence counterSuffix = attrs.getTitle();
            mSyntheticInputStage = new SyntheticInputStage();
            InputStage viewPostImeStage = new ViewPostImeInputStage(mSyntheticInputStage);
            InputStage nativePostImeStage = new NativePostImeInputStage(viewPostImeStage,
                    "aq:native-post-ime:" + counterSuffix);
            InputStage earlyPostImeStage = new EarlyPostImeInputStage(nativePostImeStage);
            InputStage imeStage = new ImeInputStage(earlyPostImeStage,
                    "aq:ime:" + counterSuffix);
            InputStage viewPreImeStage = new ViewPreImeInputStage(imeStage);
            InputStage nativePreImeStage = new NativePreImeInputStage(viewPreImeStage,
                    "aq:native-pre-ime:" + counterSuffix);

            mFirstInputStage = nativePreImeStage;
            mFirstPostImeInputStage = earlyPostImeStage;
            mPendingInputEventQueueLengthCounterName = "aq:pending:" + counterSuffix;
        }
    }
}

首先会向SurfaceFlinger注册vsync信号,等下一个vsync信号到来时就可以开始绘制;然后创建Java层的InputChannel,而它基本没有自己的实现,仅仅是通过JNI调用native方法完成功能的实现;随后将其传递给Session.addToDisplayAsUser完成InputChannel的初始化;接着用该InputChannel注册WindowInputEventReceiver来监听native层传递的输入事件;最后按照责任链的方式来处理输入事件;

1.6 Session.addToDisplayAsUser

[-> Session.java]

public int addToDisplayAsUser(IWindow window, int seq, WindowManager.LayoutParams attrs,
        int viewVisibility, int displayId, int userId, Rect outFrame,
        Rect outContentInsets, Rect outStableInsets,
        DisplayCutout.ParcelableWrapper outDisplayCutout, InputChannel outInputChannel,
        InsetsState outInsetsState, InsetsSourceControl[] outActiveControls) {
           // 调用WindowManagerService.addWindow[见1.7小节]
    return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId, outFrame,
            outContentInsets, outStableInsets, outDisplayCutout, outInputChannel,
            outInsetsState, outActiveControls, userId);
}
1.7 WindowManagerService.addWindow

[-> WindowManagerService.java]

public int addWindow(Session session, IWindow client, int seq,
        LayoutParams attrs, int viewVisibility, int displayId, Rect outFrame,
        Rect outContentInsets, Rect outStableInsets,
        DisplayCutout.ParcelableWrapper outDisplayCutout, InputChannel outInputChannel,
        InsetsState outInsetsState, InsetsSourceControl[] outActiveControls,
        int requestUserId) {
    synchronized (mGlobalLock) {
        // 创建WindowState[见1.7.1小节]
        final WindowState win = new WindowState(this, session, client, token, parentWindow,
                appOp[0], seq, attrs, viewVisibility, session.mUid, userId,
                session.mCanAddInternalSystemWindow);
        final boolean openInputChannels = (outInputChannel != null
                && (attrs.inputFeatures & INPUT_FEATURE_NO_INPUT_CHANNEL) == 0);
        if  (openInputChannels) {
            // 打开InputChannel[见1.7.2小节]
            win.openInputChannel(outInputChannel);
        }
    }
}
1.7.1 WindowState的创建

[-> WindowState.java]

WindowState(WindowManagerService service, Session s, IWindow c, WindowToken token,
        WindowState parentWindow, int appOp, int seq, WindowManager.LayoutParams a,
        int viewVisibility, int ownerId, int showUserId,
        boolean ownerCanAddInternalSystemWindow, PowerManagerWrapper powerManagerWrapper) {
    super(service);
    // Session
    mSession = s;
    // ViewRootImpl.W
    mClient = c;

    if (mAttrs.type >= FIRST_SUB_WINDOW && mAttrs.type <= LAST_SUB_WINDOW) {
        // The multiplier here is to reserve space for multiple
        // windows in the same type layer.
        mBaseLayer = mPolicy.getWindowLayerLw(parentWindow)
                * TYPE_LAYER_MULTIPLIER + TYPE_LAYER_OFFSET;
        mSubLayer = mPolicy.getSubWindowLayerFromTypeLw(a.type);
        mIsChildWindow = true;

        mLayoutAttached = mAttrs.type !=
                WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
        mIsImWindow = parentWindow.mAttrs.type == TYPE_INPUT_METHOD
                || parentWindow.mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
        mIsWallpaper = parentWindow.mAttrs.type == TYPE_WALLPAPER;
    } else {
        // The multiplier here is to reserve space for multiple
        // windows in the same type layer.
        // 计算窗口基础层级
        mBaseLayer = mPolicy.getWindowLayerLw(this)
                * TYPE_LAYER_MULTIPLIER + TYPE_LAYER_OFFSET;
        mSubLayer = 0;
        mIsChildWindow = false;
        mLayoutAttached = false;
        mIsImWindow = mAttrs.type == TYPE_INPUT_METHOD
                || mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
        mIsWallpaper = mAttrs.type == TYPE_WALLPAPER;
    }
    // 创建InputWindowHandle,它将持有ActivityRecord中InputApplicationHandle的引用
    // 我们在第三篇寻找焦点窗口和焦点应用的章节中分析过它们的作用
    mInputWindowHandle = new InputWindowHandle(
            mActivityRecord != null ? mActivityRecord.mInputApplicationHandle : null,
                getDisplayId());
}
1.7.2 WindowState.openInputChannel

[-> WindowState.java]

void openInputChannel(InputChannel outInputChannel) {
    if (mInputChannel != null) {
        throw new IllegalStateException("Window already has an input channel.");
    }
    String name = getName();
    // 创建一对InputChannel,分别代表客户端和服务端[见1.8小节]
    InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
    // 服务端
    mInputChannel = inputChannels[0];
    // 客户端
    mClientChannel = inputChannels[1];
    // 将服务端InputChannel注册到native[见1.10节]
    mWmService.mInputManager.registerInputChannel(mInputChannel);
    mInputWindowHandle.token = mInputChannel.getToken();
    if (outInputChannel != null) {
        // 将客户端InputChannel返回给ViewRootImpl
        mClientChannel.transferTo(outInputChannel);
        mClientChannel.dispose();
        mClientChannel = null;
    } else {
        // If the window died visible, we setup a dummy input channel, so that taps
        // can still detected by input monitor channel, and we can relaunch the app.
        // Create dummy event receiver that simply reports all events as handled.
        mDeadWindowEventReceiver = new DeadWindowEventReceiver(mClientChannel);
    }
    mWmService.mInputToWindowMap.put(mInputWindowHandle.token, this);
}
1.8 InputChannel.openInputChannelPair

[-> InpuChannel.java]

public static InputChannel[] openInputChannelPair(String name) {
    if (name == null) {
        throw new IllegalArgumentException("name must not be null");
    }

    if (DEBUG) {
        Slog.d(TAG, "Opening input channel pair '" + name + "'");
    }
    // 调用JNI方法[见1.8.1小节]
    return nativeOpenInputChannelPair(name);
}
1.8.1 nativeOpenInputChannelPair

[-> android_view_InpuChannel.cpp]

static jobjectArray android_view_InputChannel_nativeOpenInputChannelPair(JNIEnv* env,
        jclass clazz, jstring nameObj) {
    ScopedUtfChars nameChars(env, nameObj);
    std::string name = nameChars.c_str();

    sp<InputChannel> serverChannel;
    sp<InputChannel> clientChannel;
    // 调用native层的InputChannel::openInputChannelPair[见1.9小节]
    status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
    
   
    jobjectArray channelPair = env->NewObjectArray(2, gInputChannelClassInfo.clazz, nullptr);
    // [见1.8.2小节]
    jobject serverChannelObj = android_view_InputChannel_createInputChannel(env, serverChannel);

    jobject clientChannelObj = android_view_InputChannel_createInputChannel(env, clientChannel);
    // 将客户端和服务端的InputChannel赋值给channelPair并返回
    env->SetObjectArrayElement(channelPair, 0, serverChannelObj);
    env->SetObjectArrayElement(channelPair, 1, clientChannelObj);
    return channelPair;
}
1.8.2 createInputChannel

[-> android_view_InpuChannel.cpp]

static jobject android_view_InputChannel_createInputChannel(JNIEnv* env,
        sp<InputChannel> inputChannel) {
    // 创建NativeInputChannel并保存InputChannel
    std::unique_ptr<NativeInputChannel> nativeInputChannel =
            std::make_unique<NativeInputChannel>(inputChannel);
    // 创建结构体gInputChannelClassInfo,并让其持有NativeInputChannel的引用
    jobject inputChannelObj = env->NewObject(gInputChannelClassInfo.clazz,
            gInputChannelClassInfo.ctor);
    if (inputChannelObj) {
        android_view_InputChannel_setNativeInputChannel(env, inputChannelObj,
                 nativeInputChannel.release());
    }
    return inputChannelObj;
}
static void android_view_InputChannel_setNativeInputChannel(JNIEnv* env, jobject inputChannelObj,
        NativeInputChannel* nativeInputChannel) {
    env->SetLongField(inputChannelObj, gInputChannelClassInfo.mPtr,
             reinterpret_cast<jlong>(nativeInputChannel));
}
1.9 InputChannel.openInputChannelPair

[-> InputTransport.java]

status_t InputChannel::openInputChannelPair(const std::string& name,
        sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
    int sockets[2];
    // InputChannelPair实际上就是一对socket,它们分别可以用来读写数据
    if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
        status_t result = -errno;
        ALOGE("channel '%s' ~ Could not create socket pair.  errno=%d",
                name.c_str(), errno);
        outServerChannel.clear();
        outClientChannel.clear();
        return result;
    }

    int bufferSize = SOCKET_BUFFER_SIZE;
    // 分别设置服务端发送和接收数据的buffer大小
    setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
    setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
    // 分别设置客户端发送和接收数据的buffer大小
    setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
    setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
    
    // token是一个BBinder,代表binder的服务端
    sp<IBinder> token = new BBinder();
    
    std::string serverChannelName = name + " (server)";
    // 服务端的socket fd
    android::base::unique_fd serverFd(sockets[0]);
    // 创建native层服务端的InputChannel[见1.9.1小节]
    outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
    
    std::string clientChannelName = name + " (client)";
    // 客户端的socket fd
    android::base::unique_fd clientFd(sockets[1]);
    // 创建native层客户端的InputChannel
    outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
    return OK;
}
1.9.1 InputChannel.create

[-> InputTransport.java]

sp<InputChannel> InputChannel::create(const std::string& name, android::base::unique_fd fd,
                                      sp<IBinder> token) {
    const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
    if (result != 0) {
        LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
                         strerror(errno));
        return nullptr;
    }
    return new InputChannel(name, std::move(fd), token);
}
// InputChannel保存了名称,socket的文件描述符以及BBinder
InputChannel::InputChannel(const std::string& name, android::base::unique_fd fd, sp<IBinder> token)
      : mName(name), mFd(std::move(fd)), mToken(token) {
    if (DEBUG_CHANNEL_LIFECYCLE) {
        ALOGD("Input channel constructed: name='%s', fd=%d", mName.c_str(), mFd.get());
    }
}
1.10 registerInputChannel

[-> InputManagerService.java]

public void registerInputChannel(InputChannel inputChannel) {
    if (inputChannel == null) {
        throw new IllegalArgumentException("inputChannel must not be null.");
    }
    // 同样调用到JNI[见1.10.1小节]
    nativeRegisterInputChannel(mPtr, inputChannel);
}
1.10.1 registerInputChannel

[-> com_android_server_input_InputManagerService.java]

static void nativeRegisterInputChannel(JNIEnv* env, jclass /* clazz */,
        jlong ptr, jobject inputChannelObj) {
    NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
    // 获取之前保存的InputChannel
    sp<InputChannel> inputChannel = android_view_InputChannel_getInputChannel(env,
            inputChannelObj);
    // 调用NativeInputManager->registerInputChannel
    status_t status = im->registerInputChannel(env, inputChannel);
}
status_t NativeInputManager::registerInputChannel(JNIEnv* /* env */,
        const sp<InputChannel>& inputChannel) {
    ATRACE_CALL();
    // 通过inputflinger端的InputManager获取InputDispatcher并调用其registerInputChannel[见1.11小节]
    return mInputManager->getDispatcher()->registerInputChannel(inputChannel);
}
1.11 InputDispatcher.registerInputChannel

[-> InputDispatcher.java]

status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
    { // acquire lock
        std::scoped_lock _l(mLock);
        sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
        // 判断是否已存在InputChannel对应的Connection
        if (existingConnection != nullptr) {
            ALOGW("Attempted to register already registered input channel '%s'",
                  inputChannel->getName().c_str());
            return BAD_VALUE;
        }
        // 根据InputChannel创建Connection
        sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
    
        int fd = inputChannel->getFd();
        // 更新mConnectionsByFd
        mConnectionsByFd[fd] = connection;
        // 更新mInputChannelsByToken
        mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
    
        mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
    } // release lock
    
    // Wake the looper because some connections have changed.
    mLooper->wake();
    return OK;
}

以上是关于Android 11.0源码系列之IMSInputChannel的主要内容,如果未能解决你的问题,请参考以下文章

Android 11.0源码系列之PMSinstalld

Android 11.0源码系列之IMSInputManagerService

Android 11.0源码系列之IMSInputManager

Android 11.0源码系列之IMSInputDispatcher

Android 11.0源码系列之PMSPackageManagerService的创建

Android 11.0源码系列之IMSInputReader