class
isAssignableFrom,判断class之间的继承关系
接口,父类.class .isAssignableFrom(子.class)
anr
Activity
主要是在c层,当有等待窗口焦点的操作时,检查是否有超时
C层会回调
InputManagerService API 31已经没有notifyANR
// Native callback.
private long notifyANR(InputApplicationHandle inputApplicationHandle,
InputWindowHandle inputWindowHandle, String reason) {
// mWindowManagerCallbacks == InputMonitor
return mWindowManagerCallbacks.notifyANR(
inputApplicationHandle, inputWindowHandle, reason);
}
//InputMonitor 特别注意,API 31不是这个了InputMonitor 不再实现 WindowManagerCallback
public long notifyANR{
long timeout = ActivityManager.getService().inputDispatchingTimedOut(
windowState.mSession.mPid, aboveSystem, reason);
}
//ActivityManagerService
@Override
public long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) {
if (inputDispatchingTimedOut(proc, null, null, aboveSystem, reason)) {
return -1;
}
return timeout;
}
public boolean inputDispatchingTimedOut{
mHandler.post(new Runnable() {
@Override
public void run() {
//在这里通知app无响应了
mAppErrors.appNotResponding(proc, activity, parent, aboveSystem, annotation);
}
});
}
return true;
广播
ActivityManagerService 调用 BroadcastQueue . processNextBroadcast 这个方法在
//我们通过 BroadcastRecord.ordered 找到关键代码,判断是否是有序广播
final void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) {
broadcastTimeoutLocked(false)
}
看看这个超时怎么弄的
final void broadcastTimeoutLocked(boolean fromMsg) {
if (fromMsg) {
mPendingBroadcastTimeoutMessage = false;
}
//只有有序才超时
if (mOrderedBroadcasts.size() == 0) {
return;
}
long now = SystemClock.uptimeMillis();
//注意这里,拿的是有序广播
BroadcastRecord r = mOrderedBroadcasts.get(0);
......
}
结论,其实并行广播没有定时anr,串行的才有,串行广播就是context.sendOrderedBroadcast
前台广播和后台广播
在activityManagerService里有
// How long we allow a receiver to run before giving up on it.
static final int BROADCAST_FG_TIMEOUT = 10*1000;
static final int BROADCAST_BG_TIMEOUT = 60*1000;
是前台广播还是后台广播通过Intent.FLAG_RECEIVER_FOREGROUND
一般广播都是后台广播,队列比较,如果是希望先呗处理的广播,就用前台广播
Service
Service处理anr主要是在ActiveServices这个类里
ActiveServices
// How long we wait for a service to finish executing.
static final int SERVICE_TIMEOUT = 20*1000;
// How long we wait for a service to finish executing.
static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
前台service的 anr时间为20秒,后台为200秒
startServiceLocked -> realStartServiceLocked -> bumpServiceExecutingLocked
if (timeoutNeeded && r.app.executingServices.size() == 1) {
scheduleServiceTimeoutLocked(r.app);
}
void scheduleServiceTimeoutLocked(ProcessRecord proc) {
if (proc.executingServices.size() == 0 || proc.thread == null) {
return;
}
Message msg = mAm.mHandler.obtainMessage(
ActivityManagerService.SERVICE_TIMEOUT_MSG);
msg.obj = proc;
mAm.mHandler.sendMessageDelayed(msg,
proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
}
ContentProvider
之前他的超时时间直接写在ActivityManagerService里
为 CONTENT_PROVIDER_PUBLISH_TIMEOUT = 10*1000。
但我看31 以后已经改用 ContentResolver.CONTENT_PROVIDER_PUBLISH_TIMEOUT_MILLIS
app开始启动时间为10秒
static final int PROC_START_TIMEOUT = 10*1000;
WatchDog
检查主线程或者关键服务是否存在阻塞和死锁
为什么用喜欢用String 做hashmap的key
1,string不可变,final类型char数组,equal比对的事char数组的直
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = length();
if (n == anotherString.length()) {
int i = 0;
while (n-- != 0) {
if (charAt(i) != anotherString.charAt(i))
return false;
i++;
}
return true;
}
}
return false;
}
2,保存了hash值,下次再用就可以拿到,效率快,
/** Cache the hash code for the string */
private int hash; // Default to 0
okhttp
五层拦截器 自定义应用层拦截器-》重试拦截器 -> 设置基本头信息 -> 缓存拦截器-> 重用socket拦截器 -> 用户自定义网络拦截器 -> 发送请求拦截器
handler.postRunable()
最后一路执行到handler.dispatchMessage
public void dispatchMessage(Message msg) {
//这个callback就是runable
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
IdleHandler
这个方法是在MessageQueue.next()里执行的
Message next() {
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
//这里执行
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
}
handler.runWithScissors
其实就是BlockingRunnable.postAndWait(Handler handler,long timeOut)
postAndWait锁住BlockingRunnable this,执行完handler.post(this) 以后进入wait等 待状态,还是个isDone的循环等待,就是呗唤醒以后发现isDone = false就继续等代,run方法锁住自身,结束完以后notifyAll
app创建流程
AT.main
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
at.attach
//binder
final IActivityManager mgr = ActivityManager.getService();
try {
//mAppThread = applicationThread
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
ActivityManagerService
@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
synchronized (this) {
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
}
}
attachApplicationLocked
private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
int pid, int callingUid, long startSeq) {
//ApplicationThread
thread.bindApplication(...)
}
ActivityThread
private void handleBindApplication(AppBindData data) {
final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
mInstrumentation = new Instrumentation();
//data = = AppBindData , data.info == loadApk
//注意这里传进来空,所以里面的callApplicationOnCreate 不执行
app = data.info.makeApplication(data.restrictedBackupMode, null);
installContentProviders(app, data.providers);
mInstrumentation.callApplicationOnCreate(app);
}
LoadApk
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
//因为参数是空,这里不执行
if (instrumentation != null) {
instrumentation.callApplicationOnCreate(app);
}
}
Instrumentation
public Application newApplication(ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
Application app = getFactory(context.getPackageName())
.instantiateApplication(cl, className);
app.attach(context);
return app;
}
Activity 启动流程
如果app没创建走上面,如果app创建了
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
}
//Instrumentation
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
//走到activityManagerService
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
checkStartActivityResult(result, intent);
}
//activityManagerService
public final int startActivityAsUser{
return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setMayWait(userId)
.execute();
}
//ActivityStarter
private int startActivityUnchecked {
//ActivityStack
//移动到栈顶
mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
mOptions);
mSupervisor.resumeFocusedStackTopActivityLocked();
}
//ActivityStackSupervisor activity栈监督人
boolean resumeFocusedStackTopActivityLocked{
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
//ActivityStack
private boolean resumeTopActivityInnerLocked{
//app已经创建
if (next.app != null && next.app.thread != null) {
mStackSupervisor.startSpecificActivityLocked(next, true, false);
}
app没有创建
else{
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
}
//ActivityStackSupervisor
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
if (app != null && app.thread != null) {
realStartActivityLocked(r, app, andResume, checkConfig);
return;
// If a dead object exception was thrown -- fall through to
// restart the application.
}
//activityManager 叫zygote 开启进程
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
final boolean realStartActivityLocked{
//加入LaunchActivityItem ,并且吧intent 放进去了
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global
// and override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo));
//这里加入了ResumeActivityItem
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
//ClientLifecycleManager.scheduleTransaction
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}
//ClientTransaction
public void schedule() throws RemoteException {
//mClient 是ApplicationThread
mClient.scheduleTransaction(this);
}
//ApplicationThread
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
// ActivityThread 其实是其副类 ClientTransactionHandler
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
//ActivityThread ,注意这是hook点,可以从ClientTransaction 拿出intent进行修改
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
if (isSystem()) {
// Client transactions inside system process are recycled on the client side
// instead of ClientLifecycleManager to avoid being cleared before this
// message is handled.
transaction.recycle();
}
// TODO(lifecycler): Recycle locally scheduled transactions.
break;
//TransactionExecutor
//这个就是ActivtyThread
public TransactionExecutor(ClientTransactionHandler clientTransactionHandler) {
executeCallbacks(transaction);
}
public void executeCallbacks(ClientTransaction transaction) {
//ClientTransactionItem 其实LaunchActivityItem
item.execute(mTransactionHandler, token, mPendingActions);
//lifecycleItem 其实ResumeActivityItem。getTargetState == ON_RESUME
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
//ResumeActivityItem
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
}
//LaunchActivityItem
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
ActivityClientRecord r = client.getLaunchingActivity(token);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
//TransactionExecutor
private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
ClientTransaction transaction) {
// 这里path应该得出onStart
performLifecycleSequence(r, path, transaction);
}
//path为onStart
private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
ClientTransaction transaction) {
final int size = path.size();
for (int i = 0, state; i < size; i++) {
state = path.get(i);
if (DEBUG_RESOLVER) {
Slog.d(TAG, tId(transaction) + "Transitioning activity: "
+ getShortActivityName(r.token, mTransactionHandler)
+ " to state: " + getStateName(state));
}
switch (state) {
case ON_CREATE:
mTransactionHandler.handleLaunchActivity(r, mPendingActions,
null /* customIntent */);
break;
case ON_START: //执行这个
mTransactionHandler.handleStartActivity(r, mPendingActions,
null /* activityOptions */);
break;
case ON_RESUME:
mTransactionHandler.handleResumeActivity(r, false /* finalStateRequest */,
r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
break;
case ON_PAUSE:
mTransactionHandler.handlePauseActivity(r, false /* finished */,
false /* userLeaving */, 0 /* configChanges */, mPendingActions,
"LIFECYCLER_PAUSE_ACTIVITY");
break;
case ON_STOP:
mTransactionHandler.handleStopActivity(r, 0 /* configChanges */,
mPendingActions, false /* finalStateRequest */,
"LIFECYCLER_STOP_ACTIVITY");
break;
case ON_DESTROY:
mTransactionHandler.handleDestroyActivity(r, false /* finishing */,
0 /* configChanges */, false /* getNonConfigInstance */,
"performLifecycleSequence. cycling to:" + path.get(size - 1));
break;
case ON_RESTART:
mTransactionHandler.performRestartActivity(r, false /* start */);
break;
default:
throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
}
}
//ResumeActivityItem
@Override
public void execute(ClientTransactionHandler client, ActivityClientRecord r,
PendingTransactionActions pendingActions) {
client.handleResumeActivity(r, true /* finalStateRequest */, mIsForward,
"RESUME_ACTIVITY");
;
}
//ActivityThread
public Activity handleLaunchActivity{
final Activity a = performLaunchActivity(r, customIntent);
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
//这里其实之前创建好了就会直接返回的
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback,
r.assistToken, r.shareableActivityToken);
//设置主题
if (theme != 0) {
activity.setTheme(theme);
}
//执行构造方法
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
//设置状态为onCreate,后面在TransctionExcutor里还用到生命周期差什么判断
r.setState(ON_CREATE);
}
@Override
public void handleStartActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, ActivityOptions activityOptions) {
// Start
activity.performStart("handleStartActivity");
r.setState(ON_START);
}
//finalStateRequest = true
@Override
public void handleResumeActivity(ActivityClientRecord r, boolean finalStateRequest,
boolean isForward, String reason) {
performResumeActivity(r, finalStateRequest, reason)
}
public boolean performResumeActivity{
r.activity.performResume(r.startsNotResumed, reason);
}