当输入事件长时间未响应,则会发生ANR。输入事件ANR超时时间一般为5s。在InputDispatcher分发输入事件的过程中,会监控是否发生了ANR。具体是在执行findFocusedWindowTargetsLocked()方法时,如果当前窗口还未准备好处理输入事件,则会调用handleTargetsNotReadyLocked()方法,判断是否发生了ANR。判断的依据是等待的时间是否超过了5s,如果超过了5s,则执行onANRLocked()方法,发生ANR通知。
接下来将从findFocusedWindowTargetsLocked()开始分析,ANR产生的过程。
2.1 InputDispatcher.findFocusedWindowTargetsLocked()
int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
const EventEntry* entry, Vector& inputTargets, nsecs_t* nextWakeupTime) {
int32_t injectionResult;
String8 reason;
if (mFocusedWindowHandle == NULL) {
if (mFocusedApplicationHandle != NULL) {
injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
mFocusedApplicationHandle, NULL, nextWakeupTime,
"Waiting because no window has focus but there is a "
"focused application that may eventually add a window "
"when it finishes starting up.");//当没有找到聚焦的窗口时,见2.3
goto Unresponsive;
}
goto Failed;
}
reason = checkWindowReadyForMoreInputLocked(currentTime,
mFocusedWindowHandle, entry, "focused");//检查窗口是否准备接受多个输入事件,见2.2
if (!reason.isEmpty()) {
injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, reason.string());//不能接受处理多个输入事件,即当前正在处理其他事件,需要等待,见2.3
goto Unresponsive;
}
.....
}
在findFocusedWindowTargetsLocked()方法中,有两种情况会执行handleTargetsNotReadyLocked()方法,一种是当前没有获取焦点的窗口,另外一种是当前正在处理其他事件,不支持窗口处理更多的输入事件,需要等待。
2.2 InputDispatcher.checkWindowReadyForMoreInputLocked()
String8 InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
const sp& windowHandle, const EventEntry* eventEntry,
const char* targetType) {
// 1. 窗口被暂停了,继续等待
if (windowHandle->getInfo()->paused) {
return String8::format("Waiting because the %s window is paused.", targetType);
}
// 2. 窗口连接还未被注册,继续等待
ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
if (connectionIndex < 0) {
return String8::format("Waiting because the %s window's input channel is not "
"registered with the input dispatcher. The window may be in the process "
"of being removed.", targetType);
}
// 3. 连接已经死亡了,继续等待
sp connection = mConnectionsByFd.valueAt(connectionIndex);
if (connection->status != Connection::STATUS_NORMAL) {
return String8::format("Waiting because the %s window's input connection is %s."
"The window may be in the process of being removed.", targetType,
connection->getStatusLabel());
}
// 4. 连接上的队列已经满了,继续等待
if (connection->inputPublisherBlocked) {
return String8::format("Waiting because the %s window's input channel is full. "
"Outbound queue length: %d. Wait queue length: %d.",
targetType, connection->outboundQueue.count(), connection->waitQueue.count());
}
if (eventEntry->type == EventEntry::TYPE_KEY) {
// 5.按键事件必须等待所有之前的输入事件处理完了,才能继续处理下一个,因为之前的按键事件可能会对聚焦的窗口有影响.
if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
return String8::format("Waiting to send key event because the %s window has not "
"finished processing all of the input events that were previously "
"delivered to it. Outbound queue length: %d. Wait queue length: %d.",
targetType, connection->outboundQueue.count(), connection->waitQueue.count());
}
}else{
// 6.因为应用没有响应,等待队列堆积了很多触摸事件,此时将触发ANR。
if (!connection->waitQueue.isEmpty()
&& currentTime >= connection->waitQueue.head->deliveryTime
+ STREAM_AHEAD_EVENT_TIMEOUT) {//STREAM_AHEAD_EVENT_TIMEOUT为500ms
return String8::format("Waiting to send non-key event because the %s window has not "
"finished processing certain input events that were delivered to it over "
"%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
connection->waitQueue.count(),
(currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
}
}
return String8::empty();
}
可以看到窗口不能处理更多输入事件的原因大概有6类,即产生ANR的原因大致有6类:
按键事件必须等待所有之前的输入事件处理完了,才能继续处理下一个,因为之前的按键事件可能会对聚焦的窗口有影响,因此按键事件必须串行处理。
触摸事件总是可以立即发送给窗口,因为用户想要触摸他们当前所看到的。尽管窗口焦点可能改变或者一个新的窗口出现,触摸事件总是传递给当前出现在屏幕上的窗口。与按键事件一样,触摸事件也是传递给聚焦的窗口。与按键事件不一样的是,触摸事件一般不会把焦点转移到其他窗口,并且触摸事件没有要求串行处理。因此,触摸事件的处理更倾向于快速地分发,来提高效率和减少延迟。
2.3 InputDispatcher.handleTargetsNotReadyLocked()
int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
const EventEntry* entry,
const sp& applicationHandle,
const sp& windowHandle,
nsecs_t* nextWakeupTime, const char* reason) {
if (applicationHandle == NULL && windowHandle == NULL) {
.....
}else{//有聚焦应用或者聚焦窗口
if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
nsecs_t timeout;//超时时间
if (windowHandle != NULL) {
timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);//聚焦窗口的超时时间,为5s
} else if (applicationHandle != NULL) {//聚焦应用的超时时间,为5s
timeout = applicationHandle->getDispatchingTimeout(
DEFAULT_INPUT_DISPATCHING_TIMEOUT);
} else {
timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;//默认超时时间为5s
}
}
mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;//将等待原因设置为INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,在调用resetANRTimeoutsLocked()方法时会设置INPUT_TARGET_WAIT_CAUSE_NONE
mInputTargetWaitStartTime = currentTime;//记录等待开始时间为当前时间
mInputTargetWaitTimeoutTime = currentTime + timeout;//记录等待超时时间为当前时间+5s
mInputTargetWaitTimeoutExpired = false;
mInputTargetWaitApplicationHandle.clear();
if (windowHandle != NULL) {
mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
}
if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
mInputTargetWaitApplicationHandle = applicationHandle;
}
}
if (currentTime >= mInputTargetWaitTimeoutTime) {//当前时间大于等待超时时间,即等待时间超过5s
onANRLocked(currentTime, applicationHandle, windowHandle,
entry->eventTime, mInputTargetWaitStartTime, reason);//发送ANR通知,见2.4
*nextWakeupTime = LONG_LONG_MIN;//将唤醒时间设置为最小值,即立即唤醒poll循环处理下一个输入事件
return INPUT_EVENT_INJECTION_PENDING;
} else {
if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {//没有超时,更新下次唤醒时间
*nextWakeupTime = mInputTargetWaitTimeoutTime;
}
return INPUT_EVENT_INJECTION_PENDING;
}
}
在首次进入handleTargetsNotReadyLocked()方法的时候,mInputTargetWaitCause的值不为INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,因此会去获取一个超时时间,并记录等待的开始的时间、等待超时时间,等待的原因为INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY。这样当下一个输入事件调用handleTargetsNotReadyLocked()方法时,如果mInputTargetWaitCause的值还没有被改变,仍然为INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,则直接进入(currentTime >= mInputTargetWaitTimeoutTime)的判断。如果超时等待时间大于5s,则满足该条件,进入onANRLocked()方法,发送ANR通知。
在resetANRTimeoutsLocked()方法中,会将mInputTargetWaitCause的值设置为INPUT_TARGET_WAIT_CAUSE_NONE,这样下次再调用handleTargetsNotReadyLocked()方法时,会重新设置超时等待时间,(currentTime >= mInputTargetWaitTimeoutTime)条件判断就不会为true,也就不会进入onANRLocked()方法进行处理。
resetANRTimeoutsLocked()方法的实现如下:
void InputDispatcher::resetANRTimeoutsLocked() {
// Reset input target wait timeout.
mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
mInputTargetWaitApplicationHandle.clear();
}
2.4 InputDispatcher.onANRLocked()
void InputDispatcher::onANRLocked(
nsecs_t currentTime, const sp& applicationHandle,
const sp& windowHandle,
nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
float dispatchLatency = (currentTime - eventTime) * 0.000001f;//分发延迟
float waitDuration = (currentTime - waitStartTime) * 0.000001f;//等待延迟
ALOGI("Application is not responding: %s. "
"It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
dispatchLatency, waitDuration, reason);
// 构建ANR信息
time_t t = time(NULL);
struct tm tm;
localtime_r(&t, &tm);
char timestr[64];
strftime(timestr, sizeof(timestr), "%F %T", &tm);
mLastANRState.clear();
mLastANRState.append(INDENT "ANR:\n");
mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
mLastANRState.appendFormat(INDENT2 "Window: %s\n",
getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
dumpDispatchStateLocked(mLastANRState);
CommandEntry* commandEntry = postCommandLocked(
& InputDispatcher::doNotifyANRLockedInterruptible);//发送命令到命令队列中,等待执行,见2.5
commandEntry->inputApplicationHandle = applicationHandle;
commandEntry->inputWindowHandle = windowHandle;
commandEntry->reason = reason;
}
在onANRLocked()方法中,主要是构建ANR信息,然后将doNotifyANRLockedInterruptible()命令放入命令队列中,等待执行。
2.5 InputDispatcher.doNotifyANRLockedInterruptible()
void InputDispatcher::doNotifyANRLockedInterruptible(
CommandEntry* commandEntry) {
mLock.unlock();
nsecs_t newTimeout = mPolicy->notifyANR(
commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
commandEntry->reason);//调用NativeInputManager的notifyANR()方法,见2.6
mLock.lock();
resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
commandEntry->inputWindowHandle != NULL
? commandEntry->inputWindowHandle->getInputChannel() : NULL);//重设超时等待时间,见2.
}
在doNotifyANRLockedInterruptible()方法中,主要是调用NativeInputManager的notifyANR()方法发送ANR通知,然后根据notifyANR()方法返回的新的超时时间,调用resumeAfterTargetsNotReadyTimeoutLocked()方法重设超时等待时间。
2.6 NativeInputManager.notifyANR()
nsecs_t NativeInputManager::notifyANR(const sp& inputApplicationHandle,
const sp& inputWindowHandle, const String8& reason) {
JNIEnv* env = jniEnv();
jobject inputApplicationHandleObj =
getInputApplicationHandleObjLocalRef(env, inputApplicationHandle);
jobject inputWindowHandleObj =
getInputWindowHandleObjLocalRef(env, inputWindowHandle);
jstring reasonObj = env->NewStringUTF(reason.string());
jlong newTimeout = env->CallLongMethod(mServiceObj,
gServiceClassInfo.notifyANR, inputApplicationHandleObj, inputWindowHandleObj,
reasonObj);//调用InputManagerService的notifyANR()方法,见2.7
if (checkAndClearExceptionFromCallback(env, "notifyANR")) {
newTimeout = 0; // abort dispatch
} else {
assert(newTimeout >= 0);
}
env->DeleteLocalRef(reasonObj);
env->DeleteLocalRef(inputWindowHandleObj);
env->DeleteLocalRef(inputApplicationHandleObj);
return newTimeout;//返回超时时间
}
在NativeInputManager的初始化时,mServiceObj变量指向的Java层的InputManagerService对象,因此通过JNI调用的是Java层的InputManagerService的notifyANR()方法。
2.7 InputManagerService.notifyANR()
// Native callback.
private long notifyANR(InputApplicationHandle inputApplicationHandle,
InputWindowHandle inputWindowHandle, String reason) {
return mWindowManagerCallbacks.notifyANR(
inputApplicationHandle, inputWindowHandle, reason);//调用InputMonitor的notifyANR()方法,见2.8
}
mWindowManagerCallbacks变量指向的是InputMonitor,它是在SystemServer调用startOtherService()方法,初始化InputManagerService的时候被赋值的。
2.8 InputMonitor.notifyANR()
public long notifyANR(InputApplicationHandle inputApplicationHandle,
InputWindowHandle inputWindowHandle, String reason) {
AppWindowToken appWindowToken = null;
WindowState windowState = null;
boolean aboveSystem = false;
synchronized (mService.mWindowMap) {
if (inputWindowHandle != null) {
windowState = (WindowState) inputWindowHandle.windowState;//获取窗口对象实例
if (windowState != null) {
appWindowToken = windowState.mAppToken;
}
}
if (appWindowToken == null && inputApplicationHandle != null) {
appWindowToken = (AppWindowToken)inputApplicationHandle.appWindowToken;
}
if (windowState != null) {
Slog.i(TAG_WM, "Input event dispatching timed out "
+ "sending to " + windowState.mAttrs.getTitle()
+ ". Reason: " + reason);
// Figure out whether this window is layered above system windows.
// We need to do this here to help the activity manager know how to
// layer its ANR dialog.
int systemAlertLayer = mService.mPolicy.windowTypeToLayerLw(
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
aboveSystem = windowState.mBaseLayer > systemAlertLayer;//判断当前窗口是否在系统窗口之上
} else if (appWindowToken != null) {
Slog.i(TAG_WM, "Input event dispatching timed out "
+ "sending to application " + appWindowToken.stringName
+ ". Reason: " + reason);
} else {
Slog.i(TAG_WM, "Input event dispatching timed out "
+ ". Reason: " + reason);
}
mService.saveANRStateLocked(appWindowToken, windowState, reason);
}
if (appWindowToken != null && appWindowToken.appToken != null) {
try {
// 通知ActivityManager超时信息,让它决定是否停止分发或者继续等待
boolean abort = appWindowToken.appToken.keyDispatchingTimedOut(reason);//见2.9
if (! abort) {
// The activity manager declined to abort dispatching.
// Wait a bit longer and timeout again later.
return appWindowToken.inputDispatchingTimeoutNanos;//返回超时时间为5s
}
} catch (RemoteException ex) {
}
} else if (windowState != null) {
try {
// 通知ActivityManager超时信息,让它决定是否停止分发或者继续等待
long timeout = ActivityManagerNative.getDefault().inputDispatchingTimedOut(
windowState.mSession.mPid, aboveSystem, reason);//见2.11
if (timeout >= 0) {
// The activity manager declined to abort dispatching.
// Wait a bit longer and timeout again later.
return timeout * 1000000L; // 返回超时时间为5s
}
} catch (RemoteException ex) {
}
}
return 0; // 停止分发
}
appWindowToken变量是一个AppWindowToken对象,它里面有一个appToken成员变量,类型为IApplicationToken,IApplicationToken的实现类在ActivityRecord的内部类Token中,因此调用的是ActivityRecord.Token.keyDispatchingTimedOut()方法。
当从InputManagerService的inputDispatchingTimedOut()返回时,会返回一个新的超时时间,这个超时时间一般是5s。
2.9 ActivityRecord.Token.keyDispatchingTimedOut()
final class ActivityRecord {
......
static class Token extends IApplicationToken.Stub {
......
@Override
public boolean keyDispatchingTimedOut(String reason) {
ActivityRecord r;
ActivityRecord anrActivity;
ProcessRecord anrApp;
synchronized (mService) {
r = tokenToActivityRecordLocked(this);//获取ActivityRecord记录
if (r == null) {
return false;
}
anrActivity = r.getWaitingHistoryRecordLocked();//获取发生ANR的Activity
anrApp = r != null ? r.app : null;//获取发生ANR的进程
}
return mService.inputDispatchingTimedOut(anrApp, anrActivity, r, false, reason);//调用ActivityManagerService的inputDispatchingTimedOut(),见2.10
}
}
}
在该方法中,首先获取发生ANR的Activity和应用进程,然后调用ActivityManagerService的inputDispatchingTimedOut()方法处理ANR。
2.10 ActivityManagerService.inputDispatchingTimedOut()
public boolean inputDispatchingTimedOut(final ProcessRecord proc,
final ActivityRecord activity, final ActivityRecord parent,
final boolean aboveSystem, String reason) {
final String annotation;
if (reason == null) {
annotation = "Input dispatching timed out";
} else {
annotation = "Input dispatching timed out (" + reason + ")";
}
if (proc != null) {//进程不为空
synchronized (this) {
......
if (proc.instrumentationClass != null) {
Bundle info = new Bundle();
info.putString("shortMsg", "keyDispatchingTimedOut");
info.putString("longMsg", annotation);
finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
return true;
}
}
mHandler.post(new Runnable() {
@Override
public void run() {
mAppErrors.appNotResponding(proc, activity, parent, aboveSystem, annotation);//调用AppErrors类的appNotResponding()记录ANR发生了
}
});
}
return true;
}
当进程不为空是,最终会调用AppError类的appNotResponding()方法来记录ANR发生的一些信息。所有的ANR包括服务ANR、广播ANR以及ContentProvider的ANR都会调用到AppError类的appNotResponding()方法。
返回到2.8中,当WindowState不为空时,会调用ActivityManagerService的inputDispatchingTimedOut()方法,这个方法是一个重载的方法。
2.11 ActivityManagerService.inputDispatchingTimedOut()
public long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) {
if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
!= PackageManager.PERMISSION_GRANTED) {
throw new SecurityException("Requires permission "
+ android.Manifest.permission.FILTER_EVENTS);
}
ProcessRecord proc;
long timeout;//超时时间
synchronized (this) {
synchronized (mPidsSelfLocked) {
proc = mPidsSelfLocked.get(pid);
}
timeout = getInputDispatchingTimeoutLocked(proc);//获取超时时间,见2.12
}
if (!inputDispatchingTimedOut(proc, null, null, aboveSystem, reason)) {//见2.10
return -1;
}
return timeout;//返回超时时间
}
可以看到,不管是通过ActivityRecord.Token.keyDispatchingTimedOut()方法调用还是ActivityManagerService.inputDispatchingTimedOut()调用,最终都会调用到inputDispatchingTimedOut()方法进行处理。
2.12 ActivityManagerService.getInputDispatchingTimeoutLocked()
public static long getInputDispatchingTimeoutLocked(ProcessRecord r) {
if (r != null && (r.instrumentationClass != null || r.usingWrapper)) {
return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
}
return KEY_DISPATCHING_TIMEOUT;
}
// How long we wait until we timeout on key dispatching during instrumentation
static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
// How long we wait until we timeout on key dispatching.
static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
正常情况下,返回的超时时间是5s钟。
至此,NativeInputManager的notifyANR()方法处理完成了,并返回了一个超时时间。接着返回到2.5中,继续调用resumeAfterTargetsNotReadyTimeoutLocked()方法。
2.13 InputDispatcher.resumeAfterTargetsNotReadyTimeoutLocked()
void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
const sp& inputChannel) {
if (newTimeout > 0) {
// Extend the timeout.
mInputTargetWaitTimeoutTime = now() + newTimeout;//更新输入目标等待超时时间
} else {
// Give up.
mInputTargetWaitTimeoutExpired = true;
......
}
}
在执行完notifyANR()方法之后,根据返回的超时时间,更新输入目标等待超时时间,作为下一个输入事件的参考。当onANRLocked()方法执行完成后,会用更新mInputTargetWaitTimeoutTime变量,然后立即唤醒poll循环,处理下一个输入事件。下一个输入事件将以新的mInputTargetWaitTimeoutTime变量为参考点,查看是否发生了ANR。
ANR处理的整体流程如下:
InputDispatcher.findFocusedWindowTargetsLocked()
InputDispatcher.checkWindowReadyForMoreInputLocked()
InputDispatcher.handleTargetsNotReadyLocked()
InputDispatcher.onANRLocked()
InputDispatcher.doNotifyANRLockedInterruptible()
NativeInputManager.notifyANR()
InputManagerService.notifyANR()
InputMonitor.notifyANR()
ActivityRecord.Token.keyDispatchingTimedOut()
ActivityManagerService.inputDispatchingTimedOut()
AppError.appNotResponding()
InputDispatcher.resumeAfterTargetsNotReadyTimeoutLocked()
在分发输入事件前,如果没有待处理的输入事件,则首先会调用resetANRTimeoutsLocked()方法,将输入事件等待原因设置为INPUT_TARGET_WAIT_CAUSE_NONE,这样在执行findFocusedWindowTargetsLocked()方法时,会重新设置超时等待时间mInputTargetWaitTimeoutTime。当发生了ANR之后,会在执行完onANRLocked()方法后,更新输入事件等待超时时间mInputTargetWaitTimeoutTime。
触发resetANRTimeoutsLocked()方法调用的场景有以下几个,它们都位于InputDispatcher.cpp文件中。
在分发输入事件时,都会通过findFocusedWindowTargetsLocked()方法去查找获取焦点的窗口。如果目标窗口还未准备好处理更多的输入时间时,就调用
handleTargetsNotReadyLocked()方法进行判断是否超时了。如果超时了,则触发ANR处理过程,通知Java层继续处理ANR,然后返回新的超时时间,并用新的超时时间(默认是5s)来更新输入事件等待时间mInputTargetWaitTimeoutTime。这样下个输入事件将以更新后的mInputTargetWaitTimeoutTime为参考,继续监控下一个ANR事件。