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利用InputChannel和Connection將輸入事件分發給應用行程的程序,本篇將基于View的創建流程帶出InputChannel和Connection的創建程序,
我們通常在Activity.onCreate里通過setContentView把自己的布局決議出來并添加到DecorView上, 但是此時界面并未顯示出來,直到Activity.onResume才開始將DecorView添加到視窗上并真正呈現給用戶,同理只有此時系統才能夠開始接收用戶的輸入事件,所以InputChannel和Connection也是在這個程序中注冊和創建的;
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作為WindowManagerService和ViewRootImpl溝通的橋梁,維護了所有的ViewRootImpl,View以及其對應的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的創建程序中會創建IWindow和IWindowSession這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
標籤:其他
