说说Android的广播(5) - 广播的历史
广播的历史
AMS中的历史信息
处理完广播之后,BroadcastQueue会记录一段历史用于调试:
- mBroadcastHistory记录最近的BroadcastRecord
- mBroadcastSummaryHistory记录最近的Intent
- mSummaryHistoryEnqueueTime记录最近的enqueueTime
- mSummaryHistoryDispatchTime记录最近的dispatchTime
- mSummaryHistoryFinishTime记录最近的finishTime
具体的定义如下:
/**
* Historical data of past broadcasts, for debugging. This is a ring buffer
* whose last element is at mHistoryNext.
*/
final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
int mHistoryNext = 0;
/**
* Summary of historical data of past broadcasts, for debugging. This is a
* ring buffer whose last element is at mSummaryHistoryNext.
*/
final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
int mSummaryHistoryNext = 0;
/**
* Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
* buffer, also tracked via the mSummaryHistoryNext index. These are all in wall
* clock time, not elapsed.
*/
final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
BroadcastRecord中的历史信息
BroadcastRecord中,除了前面我们讲的这几个时间:
long enqueueClockTime; // the clock time the broadcast was enqueued
long dispatchTime; // when dispatch started on this set of receivers
long dispatchClockTime; // the clock time the dispatch started
long receiverTime; // when current receiver started for timeouts.
long finishTime; // when we finished the broadcast.
还有记录的ANR的次数:
int anrCount; // has this broadcast record hit any ANRs?
可惜这两部分信息只是被打日志调试时用到。
BroadcastQueue中记录历史的过程
BroadcastQueue中提供了addBroadcastToHistoryLocked方法来记录历史信息。
1221 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1222 if (r.callingUid < 0) {
1223 // This was from a registerReceiver() call; ignore it.
1224 return;
1225 }
1226 r.finishTime = SystemClock.uptimeMillis();
1227
1228 mBroadcastHistory[mHistoryNext] = r;
1229 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1230
1231 mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent;
1232 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime;
1233 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime;
1234 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1235 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
1236 }
其中,ringAdvance的实现是这样的。从循环计数的角度来讲,Android这段写得并不好。只在increment为+1或者-1的情况下还算工作正常吧。
1214 private final int ringAdvance(int x, final int increment, final int ringSize) {
1215 x += increment;
1216 if (x < 0) return (ringSize - 1);
1217 else if (x >= ringSize) return 0;
1218 else return x;
1219 }
addBroadcastToHistoryLocked一共被调用两次,全部都在processNextBroadcast函数中。一处是在并发队列处理完之后,另一个是在有序队列返回值以后。下节我们分析processNextBroadcast的时候,会把这些都串起来。