主頁 > 移動端開發 > Android 11.0原始碼系列之IMS(四)InputChannel

Android 11.0原始碼系列之IMS(四)InputChannel

2021-06-16 08:01:55 移動端開發

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;
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/287630.html

標籤:其他

上一篇:從Preference組件的更迭看Jetpack的前世今生

下一篇:Android 7.1開機之后APN的加載及撥號上網流程分析

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【從零開始擼一個App】Dagger2

    Dagger2是一個IOC框架,一般用于Android平臺,第一次接觸的朋友,一定會被搞得暈頭轉向。它延續了Java平臺Spring框架代碼碎片化,注解滿天飛的傳統。嘗試將各處代碼片段串聯起來,理清思緒,真不是件容易的事。更不用說還有各版本細微的差別。 與Spring不同的是,Spring是通過反射 ......

    uj5u.com 2020-09-10 06:57:59 more
  • Flutter Weekly Issue 66

    新聞 Flutter 季度調研結果分享 教程 Flutter+FaaS一體化任務編排的思考與設計 詳解Dart中如何通過注解生成代碼 GitHub 用對了嗎?Flutter 團隊分享如何管理大型開源專案 插件 flutter-bubble-tab-indicator A Flutter librar ......

    uj5u.com 2020-09-10 06:58:52 more
  • Proguard 常用規則

    介紹 Proguard 入口,如何查看輸出,如何使用 keep 設定入口以及使用實體,如何配置壓縮,混淆,校驗等規則。

    ......

    uj5u.com 2020-09-10 06:59:00 more
  • Android 開發技術周報 Issue#292

    新聞 Android即將獲得類AirDrop功能:可向附近設備快速分享檔案 谷歌為安卓檔案管理應用引入可安全隱藏資料的Safe Folder功能 Android TV新主界面將顯示電影、電視節目和應用推薦內容 泄露的Android檔案暗示了傳說中的谷歌Pixel 5a與折疊屏新機 谷歌發布Andro ......

    uj5u.com 2020-09-10 07:00:37 more
  • AutoFitTextureView Error inflating class

    報錯: Binary XML file line #0: Binary XML file line #0: Error inflating class xxx.AutoFitTextureView 解決: <com.example.testy2.AutoFitTextureView android: ......

    uj5u.com 2020-09-10 07:00:41 more
  • 根據Uri,Cursor沒有獲取到對應的屬性

    Android: 背景:呼叫攝像頭,拍攝視頻,指定保存的地址,但是回傳的Cursor檔案,只有名稱和大小的屬性,沒有其他諸如時長,連ID屬性都沒有 使用 cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATIO ......

    uj5u.com 2020-09-10 07:00:44 more
  • Android連載29-持久化技術

    一、持久化技術 我們平時所使用的APP產生的資料,在記憶體中都是瞬時的,會隨著斷電、關機等丟失資料,因此android系統采用了持久化技術,用于存盤這些“瞬時”資料 持久化技術包括:檔案存盤、SharedPreference存盤以及資料庫存盤,還有更復雜的SD卡記憶體儲。 二、檔案存盤 最基本存盤方式, ......

    uj5u.com 2020-09-10 07:00:47 more
  • Android Camera2Video整合到自己專案里

    背景: Android專案里呼叫攝像頭拍攝視頻,原本使用的 MediaStore.ACTION_VIDEO_CAPTURE, 后來因專案需要,改成了camera2 1.Camera2Video 官方demo有點問題,下載后,不能直接整合到專案 問題1.多次拍攝視頻崩潰 問題2.雙擊record按鈕, ......

    uj5u.com 2020-09-10 07:00:50 more
  • Android 開發技術周報 Issue#293

    新聞 谷歌為Android TV開發者提供多種新功能 Android 11將自動填表功能整合到鍵盤輸入建議中 谷歌宣布Android Auto即將支持更多的導航和數字停車應用 谷歌Pixel 5只有XL版本 搭載驍龍765G且將比Pixel 4更便宜 [圖]Wear OS將迎來重磅更新:應用啟動時間 ......

    uj5u.com 2020-09-10 07:01:38 more
  • 海豚星空掃碼投屏 Android 接收端 SDK 集成 六步驟

    掃碼投屏,開放網路,獨占設備,不需要額外下載軟體,微信掃碼,發現設備。支持標準DLNA協議,支持倍速播放。視頻,音頻,圖片投屏。好點意思。還支持自定義基于 DLNA 擴展的操作動作。好像要收費,沒體驗。 這里簡單記錄一下集成程序。 一 跟目錄的build.gradle添加私有mevan倉庫 mave ......

    uj5u.com 2020-09-10 07:01:43 more
最新发布
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:40:31 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:40:11 more
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:39:36 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:39:13 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:16:23 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:16:15 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:15:46 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:14:53 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:14:08 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:08:34 more