当前位置:   article > 正文

Android ANR 原理分析_android anr原理

android anr原理

ANR 简介

ANR:Application Not Responding,即“应用程序无响应”。Android 运行时,AMS 和 WMS 会监测应用程序的响应时间,如果应用程序主线程(即UI线程)在超时时间内对输入事件没有处理完毕,或者对特定操作没有执行完毕,就会上报 ANR。

ANR 的触发分为以下几类,

  • InputDispatching Timeout:输入事件(包括按键和触屏事件)在5秒内无响应,就会弹出 ANR 提示框,供用户选择继续等待程序响应或者关闭这个应用程序(也就是杀掉这个应用程序的进程)。输入超时类的 ANR 可以细分为以下两类:

    • 处理消息超时:顾名思义这一类是指因为消息处理超时而发生的 ANR,在 log,会看到 “Input dispatching timed out (Waiting because the focused window has not finished processing the input events that were previously delivered to it.)”
    • 无法获取焦点:这一类通常因为新窗口创建慢或旧窗口退出慢而造成窗口无法获得焦点从而发生 ANR,典型 Log “Reason: Waiting because no window has focus but there is a focused application that may eventually add a window when it finishes starting up.”
  • Broadcast Timeout:BroadcastReceiver在规定时间内(前台广播10秒,后台广播60秒)无法处理完成,即报出广播超时的消息。这一类型没有提示框弹出,多发于 statusbar,settings 应用中。
  • Service Timeout:Service在规定时间内(前台服务20秒,后台服务200秒)无法处理完成,即报出服务超时。这一类也不会弹框提示,偶尔会在 Bluetooth 和 wifi 中出现,但是很少碰到。
  • ContentProvider Timeout:ContentProvider 的 publish 在10s内没有完成,会报出此类 ANR。多发于android.process.media中。

产生 ANR 需要满足以下条件,

  1. 只有应用程序进程的主线程(UI 线程)响应超时才会产生 ANR。
  2. 只有达到超时时间才能触发 ANR。产生 ANR 的上下文不同,超时时间也会不同。
  3. 只有输入事件或特定操作才能触发 ANR。输入事件是指按键、触屏等设备输入事件,特定操作是指 BroadcastReceiver 和 Service 的生命周期中的各个函数。产生 ANR 的上下文不同,导致 ANR 的原因也会不同。

防止产生 ANR 的方法主要就是避免在主线程中执行耗时的操作,可以降耗时操作放入子线程中执行。耗时操作包括:

  • 数据库操作。 数据库操作尽量采用异步方法做处理
  • 初始化的数据和控件太多
  • 频繁的创建线程或者其它大对象;
  • 加载过大数据和图片;
  • 对大数据排序和循环操作;
  • 过多的广播和滥用广播;
  • 大对象的传递和共享;
  • 网络操作

InputDispatching Timeout

在 Android Input 系统中,InputDispatcher 负责将输入事件分发给 UI 主线程。UI 主线程接收到输入事件后,使用 InputConsumer 来处理事件。经过一系列的 InputStage 完成事件分发后,执行 finishInputEvent() 方法来告知 InputDispatcher 事件已经处理完成。InputDispatcher 中使用 handleReceiveCallback() 方法来处理 UI 主线程返回的消息,最终将 dispatchEntry 事件从等待队列中移除。

InputDispatching Timeout ANR 就产生于输入事件分发的过程中。InputDispatcher 分发事件过程中会检测上一个输入事件的状态,如果上一个输入事件在限定时间内没有完成分发,就会触发 ANR。InputDispatching Timeout 的默认限定时间的5s,有两处对其进行定义。

  1. frameworks/native/services/inputflinger/InputDispatcher.cpp
  2. constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
  3. frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.java
  4. static final long DEFAULT_INPUT_DISPATCHING_TIMEOUT_NANOS = 5000 * 1000000L;

Input 分发事件时,通过 InputDispatcherThread 的 threadLoop 来循环读取 Input 事件,然后使用 dispatchOnce() 进行事件分发,实际的实现在 dispatchOnceInnerLocked() 中。

  1. frameworks/native/services/inputflinger/InputDispatcher.cpp
  2. void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
  3. nsecs_t currentTime = now(); // 记录事件分发时间
  4. ......
  5. // 没有正在分发的事件时,获取一个事件
  6. if (! mPendingEvent) {
  7. if (mInboundQueue.isEmpty()) {
  8. // Inbound Queue 为空时,处理应用 switch key,根据状态生成 repeat key
  9. ......
  10. } else {
  11. // 从 Inbound Queue 中获取一个事件
  12. mPendingEvent = mInboundQueue.dequeueAtHead();
  13. traceInboundQueueLengthLocked();
  14. }
  15. ......
  16. // 重置 ANR Timeout 状态
  17. resetANRTimeoutsLocked();
  18. }
  19. ......
  20. // 根据事件类型进行分发
  21. switch (mPendingEvent->type) {
  22. case EventEntry::TYPE_CONFIGURATION_CHANGED: {
  23. // 配置改变
  24. ......
  25. case EventEntry::TYPE_DEVICE_RESET: {
  26. // 设备重置
  27. ......
  28. case EventEntry::TYPE_KEY: {
  29. // 按键输入
  30. ......
  31. done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
  32. break;
  33. }
  34. case EventEntry::TYPE_MOTION: {
  35. // 触摸屏输入
  36. ......
  37. done = dispatchMotionLocked(currentTime, typedEntry,
  38. &dropReason, nextWakeupTime);
  39. break;
  40. }
  41. ......
  42. if (done) {
  43. // 根据 dropReason 来决定是否丢弃事件
  44. if (dropReason != DROP_REASON_NOT_DROPPED) {
  45. dropInboundEventLocked(mPendingEvent, dropReason);
  46. }
  47. mLastDropReason = dropReason;
  48. releasePendingEventLocked(); // 释放正在处理的事件,也会重置 ANR timeout
  49. *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
  50. }
  51. }

接下来看具体输入事件的分发,以按键输入为例,会使用 dispatchKeyLocked() 进行分发。

  1. frameworks/native/services/inputflinger/InputDispatcher.cpp
  2. bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
  3. DropReason* dropReason, nsecs_t* nextWakeupTime) {
  4. // 新事件需要进行预处理
  5. if (! entry->dispatchInProgress) {
  6. ......
  7. }
  8. // 处理 try again 事件
  9. if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
  10. ......
  11. }
  12. // 如果 flag 为 POLICY_FLAG_PASS_TO_USER,注册事件拦截
  13. if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
  14. ......
  15. }
  16. ......
  17. // 寻找当前的焦点窗口,这里可能会触发 ANR
  18. Vector<InputTarget> inputTargets;
  19. int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
  20. entry, inputTargets, nextWakeupTime);
  21. if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
  22. return false;
  23. }
  24. ......
  25. // 分发按键
  26. dispatchEventLocked(currentTime, entry, inputTargets);
  27. return true;
  28. }

我们主要关注 ANR 的触发,看一下 findFocusedWindowTargetsLocked() 的实现。

  1. frameworks/native/services/inputflinger/InputDispatcher.cpp
  2. int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
  3. const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
  4. int32_t injectionResult;
  5. std::string reason;
  6. // 丢弃无窗口无应用的事件
  7. if (mFocusedWindowHandle == NULL) {
  8. if (mFocusedApplicationHandle != NULL) {
  9. // 有应用无窗口的状态
  10. injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
  11. mFocusedApplicationHandle, NULL, nextWakeupTime,
  12. "Waiting because no window has focus but there is a "
  13. "focused application that may eventually add a window "
  14. "when it finishes starting up.");
  15. goto Unresponsive;
  16. }
  17. ALOGI("Dropping event because there is no focused window or focused application.");
  18. injectionResult = INPUT_EVENT_INJECTION_FAILED;
  19. goto Failed;
  20. }
  21. // 权限检查
  22. if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
  23. injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
  24. goto Failed;
  25. }
  26. // 检查窗口是否 ready
  27. reason = checkWindowReadyForMoreInputLocked(currentTime,
  28. mFocusedWindowHandle, entry, "focused");
  29. if (!reason.empty()) {
  30. injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
  31. mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, reason.c_str());
  32. goto Unresponsive;
  33. }
  34. // 窗口已经准备好
  35. injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
  36. addWindowTargetLocked(mFocusedWindowHandle,
  37. InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
  38. inputTargets);
  39. ......
  40. return injectionResult;
  41. }

上述代码使用 checkWindowReadyForMoreInputLocked() 来检查窗口是否准备就绪,它使用字符串返回 window connection 的状态,当窗口正常时返回空。接下来会使用 handleTargetsNotReadyLocked() 来处理窗口未就绪的情形。

  1. frameworks/native/services/inputflinger/InputDispatcher.cpp
  2. int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
  3. const EventEntry* entry,
  4. const sp<InputApplicationHandle>& applicationHandle,
  5. const sp<InputWindowHandle>& windowHandle,
  6. nsecs_t* nextWakeupTime, const char* reason) {
  7. if (applicationHandle == NULL && windowHandle == NULL) {
  8. if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
  9. // 等待系统就绪,无窗口无应用的情形进入一次
  10. ......
  11. }
  12. } else {
  13. if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
  14. // 等待应用就绪,一个窗口进入一次
  15. ......
  16. // 设置超时,默认值都是5s
  17. nsecs_t timeout;
  18. ......
  19. mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
  20. mInputTargetWaitStartTime = currentTime; // 当前事件第一次分发时间
  21. mInputTargetWaitTimeoutTime = currentTime + timeout; // 超时时间
  22. mInputTargetWaitTimeoutExpired = false;
  23. mInputTargetWaitApplicationHandle.clear(); // 清除当前等待的应用
  24. // 设置当前等待的应用
  25. if (windowHandle != NULL) {
  26. mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
  27. }
  28. if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
  29. mInputTargetWaitApplicationHandle = applicationHandle;
  30. }
  31. }
  32. }
  33. if (mInputTargetWaitTimeoutExpired) {
  34. return INPUT_EVENT_INJECTION_TIMED_OUT;
  35. }
  36. if (currentTime >= mInputTargetWaitTimeoutTime) {
  37. // 事件分发超时,触发 ANR
  38. onANRLocked(currentTime, applicationHandle, windowHandle,
  39. entry->eventTime, mInputTargetWaitStartTime, reason);
  40. // ANR 触发时,立即唤醒下一个轮询
  41. *nextWakeupTime = LONG_LONG_MIN;
  42. return INPUT_EVENT_INJECTION_PENDING;
  43. } else {
  44. // 超时时强制唤醒轮询
  45. if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
  46. *nextWakeupTime = mInputTargetWaitTimeoutTime;
  47. }
  48. return INPUT_EVENT_INJECTION_PENDING;
  49. }
  50. }

上述代码显示了一个正常输入事件分发过程中触发 ANR 的过程,触发 ANR 的判定是在一个限定的时间内是否可以完成事件分发。正常的分发过程中会有两处位置重置 ANR timeout,

  • 获取一个新的分发事件时。
  • 事件完成分发时。
  1. void InputDispatcher::resetANRTimeoutsLocked() {
  2. // ANR timeout 重置就是重置了等待状态,清除了等待应用
  3. mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
  4. mInputTargetWaitApplicationHandle.clear();
  5. }

系统运行时,主要是以下4个场景,会有机会执行resetANRTimeoutsLocked:

  • 解冻屏幕, 系统开/关机的时刻点 (thawInputDispatchingLw, setEventDispatchingLw)
  • wms聚焦app的改变 (WMS.setFocusedApp, WMS.removeAppToken)
  • 设置input filter的过程 (IMS.setInputFilter)
  • 再次分发事件的过程(dispatchOnceInnerLocked)

触发 ANR 后,会调用 onANRLocked() 来捕获 ANR 的相关信息。大致的调用流程为,

  1. InputDispatcher::onANRLocked --> InputDispatcher::doNotifyANRLockedInterruptible
  2. --> InputManagerService.notifyANR --> InputMonitor.notifyANR
  3. --> ActivityManagerService.inputDispatchingTimedOut --> AppErrors.appNotResponding

最终在 AppErrors.appNotResponding() 中打印 log 信息、dump 栈信息、打印 CPU 信息。

Broadcast Timeout

Android 的广播机制在接收到广播进行处理时,可能会出现 receiver 处理很慢从而影响后续 receiver 接收的情形。因此,Android 对广播的接收处理增加了一个限定时间,超出限定时间将触发 ANR。需要说明,广播超时值会出现在串行广播中。并行广播因为并不存在传输的依赖关系,所以不会发生广播超时。对于不同的广播存在两个限定时间:前台广播10s和后台广播60s。

  1. frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
  2. // How long we allow a receiver to run before giving up on it.
  3. static final int BROADCAST_FG_TIMEOUT = 10*1000;
  4. static final int BROADCAST_BG_TIMEOUT = 60*1000;
  5. ......
  6. public ActivityManagerService(Context systemContext) {
  7. ......
  8. mHandlerThread = new ServiceThread(TAG,
  9. THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
  10. mHandlerThread.start();
  11. mHandler = new MainHandler(mHandlerThread.getLooper());
  12. ......
  13. // 创建广播队列,前台和后台
  14. mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
  15. "foreground", BROADCAST_FG_TIMEOUT, false);
  16. mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
  17. "background", BROADCAST_BG_TIMEOUT, true);
  18. mBroadcastQueues[0] = mFgBroadcastQueue;
  19. mBroadcastQueues[1] = mBgBroadcastQueue;
  20. ......
  21. }

 

广播队列创建时会设置超时时间,接下来直接看下广播的处理过程。

  1. frameworks/base/services/core/java/com/android/server/am/BroadcastQueue.java
  2. final void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) {
  3. BroadcastRecord r;
  4. ......
  5. // 处理并行广播
  6. while (mParallelBroadcasts.size() > 0) {
  7. ......
  8. }
  9. // 广播正在处理时,检查进程是否存活
  10. if (mPendingBroadcast != null) {
  11. ......
  12. }
  13. boolean looped = false;
  14. // 处理串行广播
  15. do {
  16. ......
  17. r = mOrderedBroadcasts.get(0);
  18. boolean forceReceive = false;
  19. // 如果广播处理超时,强行结束它
  20. int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
  21. if (mService.mProcessesReady && r.dispatchTime > 0) {
  22. long now = SystemClock.uptimeMillis();
  23. if ((numReceivers > 0) &&
  24. (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
  25. broadcastTimeoutLocked(false); // forcibly finish this broadcast
  26. forceReceive = true;
  27. r.state = BroadcastRecord.IDLE;
  28. }
  29. }
  30. ......
  31. if (r.receivers == null || r.nextReceiver >= numReceivers
  32. || r.resultAbort || forceReceive) {
  33. if (r.resultTo != null) {
  34. try {
  35. // 处理完广播,发送最终结果
  36. performReceiveLocked(r.callerApp, r.resultTo,
  37. new Intent(r.intent), r.resultCode,
  38. r.resultData, r.resultExtras, false, false, r.userId);
  39. r.resultTo = null;
  40. ......
  41. }
  42. // 撤销 BROADCAST_TIMEOUT_MSG 消息
  43. cancelBroadcastTimeoutLocked();
  44. ....
  45. }
  46. } while (r == null);
  47. // 获取下一个广播
  48. int recIdx = r.nextReceiver++;
  49. r.receiverTime = SystemClock.uptimeMillis();
  50. if (recIdx == 0) {
  51. // 在 receiver 启动时开启跟踪
  52. r.dispatchTime = r.receiverTime;
  53. r.dispatchClockTime = System.currentTimeMillis();
  54. ......
  55. }
  56. if (! mPendingBroadcastTimeoutMessage) {
  57. // 设置广播超时时间,发送 BROADCAST_TIMEOUT_MSG
  58. long timeoutTime = r.receiverTime + mTimeoutPeriod;
  59. setBroadcastTimeoutLocked(timeoutTime);
  60. }
  61. final BroadcastOptions brOptions = r.options;
  62. final Object nextReceiver = r.receivers.get(recIdx);
  63. // 处理动态注册的广播
  64. if (nextReceiver instanceof BroadcastFilter) {
  65. ......
  66. }
  67. // 处理静态注册的广播
  68. ResolveInfo info =
  69. (ResolveInfo)nextReceiver;
  70. ComponentName component = new ComponentName(
  71. info.activityInfo.applicationInfo.packageName,
  72. info.activityInfo.name);
  73. ....
  74. // 获取 receiver 对应的进程
  75. String targetProcess = info.activityInfo.processName;
  76. ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
  77. info.activityInfo.applicationInfo.uid, false);
  78. ......
  79. // 如果相应进程存在,直接进行处理
  80. if (app != null && app.thread != null && !app.killed) {
  81. try {
  82. app.addPackage(info.activityInfo.packageName,
  83. info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
  84. processCurBroadcastLocked(r, app, skipOomAdj);
  85. return;
  86. } catch (RemoteException e) {
  87. } catch (RuntimeException e) {.
  88. logBroadcastReceiverDiscardLocked(r);
  89. finishReceiverLocked(r, r.resultCode, r.resultData,
  90. r.resultExtras, r.resultAbort, false);
  91. scheduleBroadcastsLocked();
  92. r.state = BroadcastRecord.IDLE;
  93. return;
  94. }
  95. }
  96. // 如果相应进程不存在,则创建进程
  97. if ((r.curApp=mService.startProcessLocked(targetProcess,
  98. info.activityInfo.applicationInfo, true,
  99. r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
  100. "broadcast", r.curComponent,
  101. (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
  102. == null) {
  103. logBroadcastReceiverDiscardLocked(r);
  104. finishReceiverLocked(r, r.resultCode, r.resultData,
  105. r.resultExtras, r.resultAbort, false);
  106. scheduleBroadcastsLocked();
  107. r.state = BroadcastRecord.IDLE;
  108. return;
  109. }
  110. mPendingBroadcast = r;
  111. mPendingBroadcastRecvIndex = recIdx;
  112. }

上述代码是广播处理的简单流程,与 ANR 触发相关的主要是两个地方,

  • 设置广播超时的消息,setBroadcastTimeoutLocked()
  • 撤销广播超时消息,cancelBroadcastTimeoutLocked()

在开始处理一个广播时,会根据超时时间来设置一个延迟发送的消息。在限定时间内,如果该消息没有被撤销就会触发 ANR。

  1. frameworks/base/services/core/java/com/android/server/am/BroadcastQueue.java
  2. final void setBroadcastTimeoutLocked(long timeoutTime) {
  3. if (! mPendingBroadcastTimeoutMessage) {
  4. // 发送延迟消息 BROADCAST_TIMEOUT_MSG
  5. Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
  6. mHandler.sendMessageAtTime(msg, timeoutTime);
  7. mPendingBroadcastTimeoutMessage = true;
  8. }
  9. }
  1. frameworks/base/services/core/java/com/android/server/am/BroadcastQueue.java
  2. private final class BroadcastHandler extends Handler {
  3. public BroadcastHandler(Looper looper) {
  4. super(looper, null, true);
  5. }
  6. @Override
  7. public void handleMessage(Message msg) {
  8. switch (msg.what) {
  9. ....
  10. case BROADCAST_TIMEOUT_MSG: {
  11. synchronized (mService) {
  12. broadcastTimeoutLocked(true);
  13. }
  14. } break;
  15. }
  16. }
  17. }
  18. ......
  19. final void broadcastTimeoutLocked(boolean fromMsg) {
  20. ......
  21. long now = SystemClock.uptimeMillis();
  22. BroadcastRecord r = mOrderedBroadcasts.get(0);
  23. if (fromMsg) {
  24. ......
  25. long timeoutTime = r.receiverTime + mTimeoutPeriod;
  26. if (timeoutTime > now) {
  27. // 如果当前时间没有达到限定时间,重新设置超时消息
  28. setBroadcastTimeoutLocked(timeoutTime);
  29. return;
  30. }
  31. }
  32. BroadcastRecord br = mOrderedBroadcasts.get(0);
  33. if (br.state == BroadcastRecord.WAITING_SERVICES) {
  34. // 广播已经处理完,正在等待 service 执行。继续处理下一条广播
  35. br.curComponent = null;
  36. br.state = BroadcastRecord.IDLE;
  37. processNextBroadcast(false);
  38. return;
  39. }
  40. ......
  41. // 获取 APP 进程
  42. if (curReceiver != null && curReceiver instanceof BroadcastFilter) {
  43. BroadcastFilter bf = (BroadcastFilter)curReceiver;
  44. if (bf.receiverList.pid != 0
  45. && bf.receiverList.pid != ActivityManagerService.MY_PID) {
  46. synchronized (mService.mPidsSelfLocked) {
  47. app = mService.mPidsSelfLocked.get(
  48. bf.receiverList.pid);
  49. }
  50. }
  51. } else {
  52. app = r.curApp;
  53. }
  54. ......
  55. // 继续处理下一条广播
  56. finishReceiverLocked(r, r.resultCode, r.resultData,
  57. r.resultExtras, r.resultAbort, false);
  58. scheduleBroadcastsLocked();
  59. if (!debugging && anrMessage != null) {
  60. // 触发 ANR
  61. mHandler.post(new AppNotResponding(app, anrMessage));
  62. }
  63. }

在广播处理完成时会撤销超时消息。

  1. final void cancelBroadcastTimeoutLocked() {
  2. if (mPendingBroadcastTimeoutMessage) {
  3. mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
  4. mPendingBroadcastTimeoutMessage = false;
  5. }
  6. }

Service Timeout

Service Timeout 发生在 Service 的启动过程中,如果在限定时间内无法完成启动就会触发 ANR。根据 Service 类型的不同,赋予前台服务和后台服务不同的超时时间。

  1. frameworks/base/services/core/java/com/android/server/am/ActiveServices.java
  2. // How long we wait for a service to finish executing.
  3. static final int SERVICE_TIMEOUT = 20*1000;
  4. // How long we wait for a service to finish executing.
  5. static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;

在 Service 的启动过程中,会根据限定时间来设置一个延迟消息,用来触发启动超时。

  1. frameworks/base/services/core/java/com/android/server/am/ActiveServices.java
  2. private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
  3. ......
  4. scheduleServiceTimeoutLocked(r.app);
  5. ......
  6. }
  7. ......
  8. private final void realStartServiceLocked(ServiceRecord r,
  9. ProcessRecord app, boolean execInFg) throws RemoteException {
  10. ......
  11. r.app = app;
  12. r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
  13. final boolean newService = app.services.add(r);
  14. bumpServiceExecutingLocked(r, execInFg, "create"); // 发送超时消息
  15. mAm.updateLruProcessLocked(app, false, null); // 更新 LRU
  16. updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
  17. mAm.updateOomAdjLocked(); // 更新 OOM ADJ
  18. boolean created = false;
  19. try {
  20. ......
  21. mAm.notifyPackageUse(r.serviceInfo.packageName,
  22. PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
  23. app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
  24. // 最终执行服务的 onCreate() 方法
  25. app.thread.scheduleCreateService(r, r.serviceInfo,
  26. mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
  27. app.repProcState);
  28. r.postNotification();
  29. created = true;
  30. ......
  31. }
  32. ......
  33. void scheduleServiceTimeoutLocked(ProcessRecord proc) {
  34. if (proc.executingServices.size() == 0 || proc.thread == null) {
  35. return;
  36. }
  37. // 设置延迟消息,用于触发服务启动超时
  38. Message msg = mAm.mHandler.obtainMessage(
  39. ActivityManagerService.SERVICE_TIMEOUT_MSG);
  40. msg.obj = proc;
  41. mAm.mHandler.sendMessageDelayed(msg,
  42. proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
  43. }

当服务启动超时,会向 AMS 发送一个 SERVICE_TIMEOUT_MSG 消息。

  1. frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
  2. final class MainHandler extends Handler {
  3. public MainHandler(Looper looper) {
  4. super(looper, null, true);
  5. }
  6. @Override
  7. public void handleMessage(Message msg) {
  8. switch (msg.what) {
  9. ......
  10. case SERVICE_TIMEOUT_MSG: {
  11. mServices.serviceTimeout((ProcessRecord)msg.obj);
  12. } break;
  13. ......
  14. }
  15. }
  16. };
  1. frameworks/base/services/core/java/com/android/server/am/ActiveServices.java
  2. void serviceTimeout(ProcessRecord proc) {
  3. String anrMessage = null;
  4. synchronized(mAm) {
  5. if (proc.executingServices.size() == 0 || proc.thread == null) {
  6. return;
  7. }
  8. final long now = SystemClock.uptimeMillis();
  9. final long maxTime = now -
  10. (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
  11. ServiceRecord timeout = null;
  12. long nextTime = 0;
  13. for (int i=proc.executingServices.size()-1; i>=0; i--) {
  14. // 寻找超时的服务
  15. ......
  16. }
  17. if (timeout != null && mAm.mLruProcesses.contains(proc)) {
  18. // 服务超时,生成超时信息
  19. ......
  20. mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
  21. mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
  22. anrMessage = "executing service " + timeout.shortName;
  23. } else {
  24. // 服务未超时,重置超时信息
  25. Message msg = mAm.mHandler.obtainMessage(
  26. ActivityManagerService.SERVICE_TIMEOUT_MSG);
  27. msg.obj = proc;
  28. mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
  29. ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
  30. }
  31. }
  32. if (anrMessage != null) {
  33. // 触发 ANR
  34. mAm.mAppErrors.appNotResponding(proc, null, null, false, anrMessage);
  35. }
  36. }

上面描述了 Service Timeout 的产生过程,如果想避免超时消息的产生,就需要在限定时间内将消息移除。移除操作在服务启动完成后进行,下面看一下真正进行服务启动的代码。

  1. frameworks/base/core/java/android/app/ActivityThread.java
  2. private void handleCreateService(CreateServiceData data) {
  3. unscheduleGcIdler();
  4. LoadedApk packageInfo = getPackageInfoNoCheck(
  5. data.info.applicationInfo, data.compatInfo);
  6. Service service = null;
  7. try {
  8. // 创建 service
  9. java.lang.ClassLoader cl = packageInfo.getClassLoader();
  10. service = packageInfo.getAppFactory()
  11. .instantiateService(cl, data.info.name, data.intent);
  12. ......
  13. try {
  14. // 创建ContextImpl对象
  15. ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
  16. context.setOuterContext(service);
  17. // 创建Application对象
  18. Application app = packageInfo.makeApplication(false, mInstrumentation);
  19. service.attach(context, this, data.info.name, data.token, app,
  20. ActivityManager.getService());
  21. service.onCreate(); // 调用服务onCreate()方法
  22. mServices.put(data.token, service);
  23. try {
  24. // 服务启动完成
  25. ActivityManager.getService().serviceDoneExecuting(
  26. data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
  27. ......
  28. }
  1. frameworks/base/services/core/java/com/android/server/am/ActiveServices.java
  2. private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
  3. boolean finishing) {
  4. r.executeNesting--;
  5. if (r.executeNesting <= 0) {
  6. if (r.app != null) {
  7. r.app.execServicesFg = false;
  8. r.app.executingServices.remove(r);
  9. if (r.app.executingServices.size() == 0) {
  10. // 当前进程中没有正在执行的 service 时,移除服务超时消息
  11. mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
  12. ......

ContentProvider Timeout

ContentProvider Timeout 发生在应用启动过程中。如果应用启动时,Provider 发布超过限定时间就会触发 ANR。应用进程创建后,会调用 attachApplicationLocked() 进行初始化。

  1. frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
  2. // How long we wait for an attached process to publish its content providers
  3. // before we decide it must be hung.
  4. static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT = 10*1000;
  5. ......
  6. private final boolean attachApplicationLocked(IApplicationThread thread,
  7. int pid, int callingUid, long startSeq) {
  8. ......
  9. // 如果应用存在 Provider,设置延迟消息处理 Provider 超时
  10. if (providers != null && checkAppInLaunchingProvidersLocked(app)) {
  11. Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG);
  12. msg.obj = app;
  13. mHandler.sendMessageDelayed(msg, CONTENT_PROVIDER_PUBLISH_TIMEOUT);
  14. }
  15. ......
  16. }

当在限定时间内没有完成 Provider 发布时,会发送消息 CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG,Handler 会进行相应处理。

  1. frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
  2. final class MainHandler extends Handler {
  3. public MainHandler(Looper looper) {
  4. super(looper, null, true);
  5. }
  6. @Override
  7. public void handleMessage(Message msg) {
  8. switch (msg.what) {
  9. ......
  10. case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: {
  11. // 处理 Provider 超时消息
  12. ProcessRecord app = (ProcessRecord)msg.obj;
  13. synchronized (ActivityManagerService.this) {
  14. processContentProviderPublishTimedOutLocked(app);
  15. }
  16. } break
  17. ......
  18. }
  19. }
  20. ......
  21. boolean removeProcessLocked(ProcessRecord app,
  22. boolean callerWillRestart, boolean allowRestart, String reason) {
  23. final String name = app.processName;
  24. final int uid = app.uid;
  25. ......
  26. // 移除mProcessNames中的相应对象
  27. removeProcessNameLocked(name, uid);
  28. ......
  29. boolean needRestart = false;
  30. if ((app.pid > 0 && app.pid != MY_PID) || (app.pid == 0 && app.pendingStart)) {
  31. int pid = app.pid;
  32. if (pid > 0) {
  33. // 杀进程前处理一些相关状态
  34. ......
  35. }
  36. // 判断是否需要重启进程
  37. boolean willRestart = false;
  38. if (app.persistent && !app.isolated) {
  39. if (!callerWillRestart) {
  40. willRestart = true;
  41. } else {
  42. needRestart = true;
  43. }
  44. }
  45. app.kill(reason, true); // 杀死进程
  46. handleAppDiedLocked(app, willRestart, allowRestart); // 回收资源
  47. if (willRestart) {
  48. removeLruProcessLocked(app);
  49. addAppLocked(app.info, null, false, null /* ABI override */);
  50. }
  51. } else {
  52. mRemovedProcesses.add(app);
  53. }
  54. return needRestart;
  55. }
  56. ......
  57. private final void processContentProviderPublishTimedOutLocked(ProcessRecord app) {
  58. // 清理 Provider
  59. cleanupAppInLaunchingProvidersLocked(app, true);
  60. // 清理应用进程
  61. removeProcessLocked(app, false, true, "timeout publishing content providers");
  62. }
  63. ......
  64. boolean cleanupAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
  65. boolean restart = false;
  66. for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) {
  67. ContentProviderRecord cpr = mLaunchingProviders.get(i);
  68. if (cpr.launchingApp == app) {
  69. if (!alwaysBad && !app.bad && cpr.hasConnectionOrHandle()) {
  70. restart = true;
  71. } else {
  72. // 移除死亡的 Provider
  73. removeDyingProviderLocked(app, cpr, true);
  74. }
  75. }
  76. }
  77. return restart;
  78. }

可以看到 ContentProvider Timeout 发生时并没有调用 AMS.appNotResponding() 方法,仅仅杀死问题进程及清理相关信息。Provider 的超时消息会在发布成功时被清除,相关代码如下。

  1. frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
  2. public final void publishContentProviders(IApplicationThread caller,
  3. List<ContentProviderHolder> providers) {
  4. ......
  5. synchronized (this) {
  6. final ProcessRecord r = getRecordForAppLocked(caller);
  7. ......
  8. final int N = providers.size();
  9. for (int i = 0; i < N; i++) {
  10. ContentProviderHolder src = providers.get(i);
  11. ......
  12. ContentProviderRecord dst = r.pubProviders.get(src.info.name);
  13. if (dst != null) {
  14. ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
  15. mProviderMap.putProviderByClass(comp, dst);
  16. ......
  17. if (wasInLaunchingProviders) {
  18. // 移除超时消息
  19. mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, r);
  20. }
  21. ......
  22. }
  23. }
  24. Binder.restoreCallingIdentity(origId);
  25. }
  26. }

 

涉及到的广播知识点可以查看文章https://blog.csdn.net/wangsen927/article/details/116302720

转自:https://segmentfault.com/a/1190000022967452 感谢作者

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/989634
推荐阅读
相关标签
  

闽ICP备14008679号