Android 插件化Hook 插件化框架 ( 从 Hook 应用角度分析 Activity 启动流程 二 | AMS 进程相关源码 | 主进程相关源码 )
Posted 韩曙亮
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 插件化Hook 插件化框架 ( 从 Hook 应用角度分析 Activity 启动流程 二 | AMS 进程相关源码 | 主进程相关源码 )相关的知识,希望对你有一定的参考价值。
android 插件化系列文章目录
【Android 插件化】插件化简介 ( 组件化与插件化 )
【Android 插件化】插件化原理 ( JVM 内存数据 | 类加载流程 )
【Android 插件化】插件化原理 ( 类加载器 )
【Android 插件化】“ 插桩式 “ 插件化框架 ( 原理与实现思路 )
【Android 插件化】“ 插桩式 “ 插件化框架 ( 类加载器创建 | 资源加载 )
【Android 插件化】“ 插桩式 “ 插件化框架 ( 注入上下文的使用 )
【Android 插件化】“ 插桩式 “ 插件化框架 ( 获取插件入口 Activity 组件 | 加载插件 Resources 资源 )
【Android 插件化】“ 插桩式 “ 插件化框架 ( 运行应用 | 代码整理 )
【Android 插件化】Hook 插件化框架 ( Hook 技术 | 代理模式 | 静态代理 | 动态代理 )
【Android 插件化】Hook 插件化框架 ( Hook 实现思路 | Hook 按钮点击事件 )
【Android 插件化】Hook 插件化框架 ( Hook Activity 启动过程 | 静态代理 )
【Android 插件化】Hook 插件化框架 ( 从 Hook 应用角度分析 Activity 启动流程 一 | Activity 进程相关源码 )
【Android 插件化】Hook 插件化框架 ( 从 Hook 应用角度分析 Activity 启动流程 二 | AMS 进程相关源码 | 主进程相关源码 )
文章目录
前言
上一篇博客 【Android 插件化】Hook 插件化框架 ( 从 Hook 应用角度分析 Activity 启动流程 一 | Activity 进程相关源码 ) 分析了 Activity 启动流程中 , Activity 进程中相关调用链涉及的源码 ;
本博客中着重分析 AMS 中涉及到的源码 和 AMS 启动主进程 Activity 源码 ;
一、ActivityManagerService 进程相关源码
1、ActivityManagerService 源码分析
在 Instrumentation 的 execStartActivity 方法中 , 最核心的代码是
int result = ActivityTaskManager.getService().startActivity(whoThread,
who.getBasePackageName(), who.getAttributionTag(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()), token,
target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
先通过 ActivityTaskManager.getService() 获取服务 ,
public class ActivityTaskManager {
/** @hide */
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
@UnsupportedAppUsage(trackingBug = 129726065)
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
new Singleton<IActivityTaskManager>() {
@Override
protected IActivityTaskManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
return IActivityTaskManager.Stub.asInterface(b);
}
};
}
调用 IActivityTaskManagerSingleton.get() 方法 , 就是调用 IActivityTaskManagerSingleton 的 create 方法 , 返回如下结果
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
return IActivityTaskManager.Stub.asInterface(b);
该 IActivityTaskManager 没有找到对应 Java 代码 , 是 AIDL 文件 ; 返回的结果是 Binder 的代理类 , 该类主要作用是使用了 Binder 机制 , 进行进程间通信 ;
获取的远程服务是 ActivityManagerService , 在 Instrumentation 中调用 ActivityTaskManager.getService().startActivity() 方法 , 就是调用 AMS ( ActivityManagerService ) 的 startActivity 方法 , 最终调用的是 AMS 的 startActivityAsUser 方法 , 在该方法中调用了 ActivityStartController mActivityStartController
成员的 obtainStarter
方法 ,
public class ActivityManagerService extends IActivityManager.Stub
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
private final ActivityStartController mActivityStartController;
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
true /*validateIncomingUser*/);
}
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
boolean validateIncomingUser) {
enforceNotIsolatedCaller("startActivity");
userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
// TODO: Switch to user app stacks here.
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();
}
}
/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
2、ActivityStarter 源码分析
/frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
a、obtainStarter 方法分析
调用 ActivityStartController 的 obtainStarter 方法 , 得到的是 ActivityStarter 方法 , Activity 的启动是由该 ActivityStarter 来完成的 ;
public class ActivityStartController {
/**
* @return A starter to configure and execute starting an activity. It is valid until after
* {@link ActivityStarter#execute} is invoked. At that point, the starter should be
* considered invalid and no longer modified or used.
*/
ActivityStarter obtainStarter(Intent intent, String reason) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}
}
b、execute 方法分析
Activity 启动过程很复杂 , 封装在 ActivityStarter 类中 , 该类有 2700 2700 2700 行代码 , 也是个重量级的类 , 因此没有在 ActivityManagerService 中定义 , 而是拆分出来 , 进行处理 ;
class ActivityStarter {
/**
* Starts an activity based on the request parameters provided earlier.
* @return The starter result.
*/
int execute() {
try {
// TODO(b/64750076): Look into passing request directly to these methods to allow
// for transactional diffs and preprocessing.
if (mRequest.mayWait) {
return startActivityMayWait(mRequest.caller, mRequest.callingUid,
mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup);
} else {
return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
mRequest.outActivity, mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup);
}
} finally {
onExecutionComplete();
}
}
}
c、startActivityMayWait 方法分析
如果需要等待 , 则调用 ActivityStarter 的 startActivityMayWait 方法 , 在该方法中需要获取调用的 进程 ID , 用户 ID ,
final int realCallingPid = Binder.getCallingPid();
final int realCallingUid = Binder.getCallingUid();
然后 Activity 任务栈管理者 mSupervisor 解析 Intent , 将解析的信息放在 ResolveInfo rInfo 中 ;
ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
0 /* matchFlags */,
computeResolveFilterUid(
callingUid, realCallingUid, mRequest.filterCallingUid));
通过 Activity 任务栈管理者 mSupervisor 解析 Activity , 将获取的 Activity 信息放在 ActivityInfo aInfo 中 ;
// Collect information about the target of the Intent.
ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
最后 , 调用 ActivityStarter 的 startActivity 方法 , 进行界面启动 ;
int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
allowPendingRemoteAnimationRegistryLookup);
d、startActivity 方法分析
ActivityStarter 中的 startActivity 方法参数较多 , 有十几个 ;
private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
SafeActivityOptions options,
boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {
return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true /* doResume */, checkedOptions, inTask, outActivity);
}
在该方法的最后调用了 startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask, outActivity)
方法 ,
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
}
在上述参数较少的 startActivity 方法中 , 调用了 startActivityUnchecked 方法 ;
// Note: This method should only be called from {@link startActivity}.
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
e、startActivityUnchecked 方法分析
在 ActivityStarter 中的 startActivityUnchecked 方法中 , 进行启动之前的初始化操作 , 如分析启动模式 LaunchMod , 解析设置的 Activity 启动标志位 Flag 等 ;
该方法中执行 Activity 启动前的操作 ;
// Note: This method should only be called from {@link startActivity}.
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
voiceInteractor);
computeLaunchingTaskFlags();
computeSourceStack();
mIntent.setFlags(mLaunchFlags);
ActivityRecord reusedActivity = getReusableIntentActivity();
}
期间调用了 ActivityStarter 类的 private final ActivityStackSupervisor mSupervisor 成员的 resumeFocusedStackTopActivityLocked 方法 ;
mSupervisor.resumeFocusedStackTopActivityLocked();
/frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
3、ActivityStackSupervisor 源码分析
ActivityStackSupervisor 的 resumeFocusedStackTopActivityLocked()
方法中 ,
调用了 boolean resumeFocusedStackTopActivityLocked( ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions)
方法 ,
在该方法中 , 判断当前的状态是否是 Resume 状态 , 如果不是 , 则调用 ActivityStack mFocusedStack 成员的 resumeTopActivityUncheckedLocked
方法 ;
public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener,
RecentTasks.Callbacks {
/** The stack currently receiving input or launching the next activity. */
ActivityStack mFocusedStack;
boolean resumeFocusedStackTopActivityLocked() {
return resumeFocusedStackTopActivityLocked(null, null, null);
}
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (!readyToResume()) {
return false;
}
if (targetStack != null && isFocusedStack(targetStack)) {
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
if (r == null || !r.isState(RESUMED)) {
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
} else if (r.isState(RESUMED)) {
// Kick off any lingering app transitions form the MoveTaskToFront operation.
mFocusedStack.executeAppTransition(targetOptions);
}
return false;
}
}
/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
4、ActivityStack 源码分析
a、resumeTopActivityUncheckedLocked 方法分析
上面分析到 Activity 调用 startActivity 调用的是 ActivityStack 的 resumeTopActivityUncheckedLocked 方法 , 在该方法中调用了 resumeTopActivityInnerLocked 方法 ;
/**
* Ensure that the top activity in the stack is resumed.
*
* @param prev The previously resumed activity, for when in the process
* of pausing; can be null to call from elsewhere.
* @param options Activity options.
*
* @return Returns true if something is being resumed, or false if
* nothing happened.
*
* NOTE: It is not safe to call this method directly as it can cause an activity in a
* non-focused stack to be resumed.
* Use {@link ActivityStackSupervisor#resumeFocusedStackTopActivityLocked} to resume the
* right activity for the current system state.
*/
@GuardedBy("mService")
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mStackSupervisor.inResumeTopActivity) {
// Don't even start recursing.
return false;
}
boolean result = false;
try {
// Protect against recursion.
mStackSupervisor.inResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options);
// When resuming the top activity, it may be necessary to pause the top activity (for
// example, returning to the lock screen. We suppress the normal pause logic in
// {@link #resumeTopActivityUncheckedLocked}, since the top activity is resumed at the
// end. We call the {@link ActivityStackSupervisor#checkReadyForSleepLocked} again here
// to ensure any necessary pause logic occurs. In the case where the Activity will be
// shown regardless of the lock screen, the call to
// {@link ActivityStackSupervisor#checkReadyForSleepLocked} is skipped.
final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
if (next == null || !next.canTurnScreenOn()) {
checkReadyForSleep();
}
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
return result;
}
/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
b、resumeTopActivityInnerLocked 方法分析
在 ActivityStack 中的 resumeTopActivityInnerLocked 方法中调用了 startPausingLocked 方法 ;
class ActivityStack<T extends StackWindowController> extends ConfigurationContainer
implements StackWindowListener {
/** Run all ActivityStacks through this */
protected final ActivityStackSupervisor mStackSupervisor;
@GuardedBy("mService")
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
if (mResumedActivity != null) {
if (DEBUG_STATES) Slog.d(TAG_STATES,
"resumeTopActivityLocked: Pausing " + mResumedActivity);
pausing |= startPausingLocked(userLeaving, false, next, false);
}
}
}
/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
该方法的调用链很长 , 有几百行代码 ;
c、startPausingLocked 方法分析
startPausingLocked 方法中 , 调用了 mService.getLifecycleManager().scheduleTransaction 方法 , 该方法用于控制 Activity 声明周期的方法 , 其中涉及 PauseActivityItem 参数 , 说明要执行的是 Activity 的 onPause 生命周期方法 ;
/**
* Start pausing the currently resumed activity. It is an error to call this if there
* is already an activity being paused or there is no resumed activity.
*
* @param userLeaving True if this should result in an onUserLeaving to the current activity.
* @param uiSleeping True if this is happening with the user interface going to sleep (the
* screen turning off).
* @param resuming The activity we are currently trying to resume or null if this is not being
* called as part of resuming the top activity, so we shouldn't try to instigate
* a resume here if not null.
* @param pauseImmediately True if the caller does not want to wait for the activity callback to
* complete pausing.
* @return Returns true if an activity now is in the PAUSING state, and we are waiting for
* it to tell us when it is done.
*/
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
ActivityRecord resuming, boolean pauseImmediately) {
mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
PauseActivityItem.obtain(prev.finishing, userLeaving,
prev.configChangeFlags, pauseImmediately));
}
注意 PauseActivityItem 专门用于处理 Activity Pause 生命周期 ;
/frameworks/base/core/java/android/app/servertransaction/PauseActivityItem.java
PauseActivityItem 继承了 ActivityLifecycleItem ,
/frameworks/base/core/java/android/app/servertransaction/ActivityLifecycleItem.java
ActivityLifecycleItem 继承了 ClientTransactionItem , ClientTransactionItem 会被 TransactionExecutor 执行 ,
/frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
执行 PauseActivityItem 后
以上是关于Android 插件化Hook 插件化框架 ( 从 Hook 应用角度分析 Activity 启动流程 二 | AMS 进程相关源码 | 主进程相关源码 )的主要内容,如果未能解决你的问题,请参考以下文章
Android 插件化Hook 插件化框架 ( 从 Hook 应用角度分析 Activity 启动流程 二 | AMS 进程相关源码 | 主进程相关源码 )
Android 插件化Hook 插件化框架 ( Hook 实现思路 | Hook 按钮点击事件 )
Android 插件化Hook 插件化框架 ( hook 插件化原理 | 插件包管理 )
Android 插件化Hook 插件化框架 ( Hook Activity 启动流程 | Hook 点分析 )
Android 插件化Hook 插件化框架总结 ( 插件包管理 | Hook Activity 启动流程 | Hook 插件包资源加载 ) ★★★