温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在Android中使用InputManagerService进行事件传递

发布时间:2020-11-25 16:47:31 来源:亿速云 阅读:372 作者:Leah 栏目:移动开发

在Android中使用InputManagerService进行事件传递?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

InputManagerService

public void start() {
 Slog.i(TAG, "Starting input manager");
 nativeStart(mPtr);
 ........
}

看到这个nativeStart,是不是倒吸一口凉气,没错,是一个native方法。不过这也没办法,毕竟底层嘛,少不了和c打交道~

static void nativeStart(JNIEnv* env, jclass /* clazz */, jlong ptr) {
 NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);

 status_t result = im->getInputManager()->start();
 if (result) {
  jniThrowRuntimeException(env, "Input manager could not be started.");
 }
}

可以看到,调用了InputManager的start方法。

status_t InputManager::start() {
 status_t result = mDispatcherThread->run("InputDispatcher", PRIORITY_URGENT_DISPLAY);
 if (result) {
  ALOGE("Could not start InputDispatcher thread due to error %d.", result);
  return result;
 }

 result = mReaderThread->run("InputReader", PRIORITY_URGENT_DISPLAY);
 if (result) {
  ALOGE("Could not start InputReader thread due to error %d.", result);

  mDispatcherThread->requestExit();
  return result;
 }

 return OK;
}

其中初始化了两个线程——ReaderThread和DispatcherThread。这两个线程的作用非常重要,前者接受来自设备的事件并且将其封装成上层看得懂的信息,后者负责把事件分发出去。可以说,我们上层的Activity或者是View的事件,都是来自于这两个线程。这里我不展开讲了,有兴趣的同学可以自行根据源码进行分析。有趣的是,DispatcherThread在轮询点击事件的过程中,采用的Looper的形式,可见Android中的源码真的是处处相关联,所以不要觉得某一部分的源码看了没用,说不定以后你就会用到了。

ViewRootImpl

从前一小节我们得知,设备的点击事件是通过InputManagerService来进行传递的,其中存在两个线程一个用于处理,一个用于分发,那么事件分发到哪里去呢?直接发到Activity或者View中吗?这显然是不合理的,所以Framework层中存在一个ViewRootImpl类,作为两者沟通的桥梁。需要注意的是,该类在老版本的源码中名为ViewRoot。

ViewRootImpl这个类是在Activity的resume生命周期中初始化的,调用了ViewRootImpl.setView函数,下面让我们看看这个函数做了什么。

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
 synchronized (this) {
  if (mView == null) {
   mView = view;
   ..........
   if ((mWindowAttributes.inputFeatures
     & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
    mInputChannel = new InputChannel();
   }
   try {
    mOrigWindowType = mWindowAttributes.type;
    mAttachInfo.mRecomputeGlobalAttributes = true;
    collectViewAttributes();

    //Attention here!!!
    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
      getHostVisibility(), mDisplay.getDisplayId(),
      mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
      mAttachInfo.mOutsets, mInputChannel);
   } catch (RemoteException e) {
    mAdded = false;
    mView = null;
    mAttachInfo.mRootView = null;
    mInputChannel = null;
    mFallbackEventHandler.setView(null);
    unscheduleTraversals();
    setAccessibilityFocus(null, null);
    throw new RuntimeException("Adding window failed", e);
   } finally {
    if (restore) {
     attrs.restore();
    }
   }
   ............
   if (mInputChannel != null) {
     if (mInputQueueCallback != null) {
      mInputQueue = new InputQueue();
      mInputQueueCallback.onInputQueueCreated(mInputQueue);
     }
     mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
       Looper.myLooper());
   }
  }
 }
}

这个方法非常的长,我先截取了一小段,看我标注的[Attention here],创建了一个InputChannel的实例,并且通过mWindowSession.addToDisplay方法将其添加到了mWindowSession中。

final IWindowSession mWindowSession;

public ViewRootImpl(Context context, Display display) {
 mContext = context;
 mWindowSession = WindowManagerGlobal.getWindowSession();
 ......
}
public static IWindowSession getWindowSession() {
 synchronized (WindowManagerGlobal.class) {
  if (sWindowSession == null) {
   try {
    InputMethodManager imm = InputMethodManager.getInstance();
    IWindowManager windowManager = getWindowManagerService();
    sWindowSession = windowManager.openSession(
      new IWindowSessionCallback.Stub() {
       @Override
       public void onAnimatorScaleChanged(float scale) {
        ValueAnimator.setDurationScale(scale);
       }
      },
      imm.getClient(), imm.getInputContext());
   } catch (RemoteException e) {
    Log.e(TAG, "Failed to open window session", e);
   }
  }
  return sWindowSession;
 }
}

mWindowSession是什么呢?通过上面的代码我们可以知道,mWindowSession就是WindowManagerService中的一个内部实例。getWindowManagerService拿到的事WindowManagerNative的proxy对象,所以由此我们可以知道,mWindowSession也是用来IPC的。

如果大家对上面一段话不是很了解,换句话说不了解Android的Binder机制的话,可以先去自行了结一下。

回到上面的setView函数,mWindowSession.addToDisplay方法肯定调用的是对应remote的addToDisplay方法,其中会调用WindowManagerService::addWindow方法去将InputChannel注册到WMS中。

看到这里大家可能会有疑问,第一小节说的是InputManagerService管理设备的事件,怎么到了这一小节就变成了和WindowManagerService打交道呢?秘密其实就在mWindowSession.addToDisplay方法中。

WindowManagerService

public int addWindow(Session session, IWindow client, int seq,
  WindowManager.LayoutParams attrs, int viewVisibility, int displayId,
  Rect outContentInsets, Rect outStableInsets, Rect outOutsets,
  InputChannel outInputChannel) {

  ..........
  if (outInputChannel != null && (attrs.inputFeatures
    & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
   String name = win.makeInputChannelName();
   InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
   win.setInputChannel(inputChannels[0]);
   inputChannels[1].transferTo(outInputChannel);

   mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle);
  }
  ...........
}

可以看到在addWindow方法中,创建了一个InputChannel的数组,数组中有两个InputChannel,第一个是remote端的,通过 mInputManager.registerInputChannel方法讲其注册到InputManager中;第二个是native端的,通过inputChannels[1].transferTo(outInputChannel)方法,将其指向outInputChannel,而outInputChannel就是前面setView传过来的那个InputChannel,也就是ViewRootImpl里的。

通过这一段代码,我们知道,当Activity初始化的时候,我们就会在WMS中注册两个InputChannel,remote端的InputChannel注册到InputManager中,用于接受ReaderThread和DispatcherThread传递过来的信息,native端的InputChannel指向ViewRootImpl中的InputChannel,用于接受remote端的InputChannel传递过来的信息。

最后,回到ViewRootImpl的setView方法的最后,有这么一句:

mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
  Looper.myLooper());

WindowInputEventReceiver,就是我们最终接受事件的接收器了。

键盘事件的传递

下面让我们看看WindowInputEventReceiver做了什么。

final class WindowInputEventReceiver extends InputEventReceiver {
 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
  super(inputChannel, looper);
 }

 @Override
 public void onInputEvent(InputEvent event) {
  enqueueInputEvent(event, this, 0, true);
 }

 @Override
 public void onBatchedInputEventPending() {
  if (mUnbufferedInputDispatch) {
   super.onBatchedInputEventPending();
  } else {
   scheduleConsumeBatchedInput();
  }
 }

 @Override
 public void dispose() {
  unscheduleConsumeBatchedInput();
  super.dispose();
 }
}

很简单,回调到onInputEvent函数的时候,就调用ViewRootImpl的enqueueInputEvent函数。

void enqueueInputEvent(InputEvent event,
  InputEventReceiver receiver, int flags, boolean processImmediately) {
 .........
 if (processImmediately) {
  doProcessInputEvents();
 } else {
  scheduleProcessInputEvents();
 }
}

可以看到,如果需要立即处理该事件,就直接调用doProcessInputEvents函数,否则调用scheduleProcessInputEvents函数加入调度。

这里我们一切从简,直接看doProcessInputEvents函数。

void doProcessInputEvents() {
 ........
 deliverInputEvent(q);
 ........
}

private void deliverInputEvent(QueuedInputEvent q) {
  Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
    q.mEvent.getSequenceNumber());
  if (mInputEventConsistencyVerifier != null) {
   mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
  }

  InputStage stage;
  if (q.shouldSendToSynthesizer()) {
   stage = mSyntheticInputStage;
  } else {
   stage = q.shouldSkipIme() &#63; mFirstPostImeInputStage : mFirstInputStage;
  }

  if (stage != null) {
   stage.deliver(q);
  } else {
   finishInputEvent(q);
  }
}

可以看到deliverInputEvent函数中,存在一个很有意思的东西叫InputStage,通过一些标记位去确定到底是用哪个InputStage去处理。

这些InputStage是在哪里初始化的呢?显示是在setView函数啦。

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;

可以看到初始化了如此多的InputStage。这些stage的调用顺序是严格控制的,Ime的意思是输入法,所以大家应该了解这些preIme和postIme是什么意思了吧?

从上面得知,最终会调用InputStage的deliver函数:

public final void deliver(QueuedInputEvent q) {
 if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) {
  forward(q);
 } else if (shouldDropInputEvent(q)) {
  finish(q, false);
 } else {
  apply(q, onProcess(q));
 }
}

其apply方法被各个子类重写的,下面我们以ViewPreImeInputStage为例:

@Override
protected int onProcess(QueuedInputEvent q) {
 if (q.mEvent instanceof KeyEvent) {
  return processKeyEvent(q);
 }
 return FORWARD;
}

private int processKeyEvent(QueuedInputEvent q) {
 final KeyEvent event = (KeyEvent)q.mEvent;
 if (mView.dispatchKeyEventPreIme(event)) {
  return FINISH_HANDLED;
 }
 return FORWARD;
}

可以看到,会调用View的dispatchKeyEventPreIme方法。看到这里,文章最开头的那个问题也就迎刃而解了,为什么在输入法弹出的情况下,监听Activity的onKeyDown没有用呢?因为该事件被输入法消耗了,对应的,就是说走到了imeStage这个InputStage中;那为什么重写View的dispatchKeyEventPreIme方法就可以呢?因为它是在ViewPreImeInputStage中被调用的,还没有轮到imeStage呢~

看完上述内容,你们掌握在Android中使用InputManagerService进行事件传递的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI