編輯:關於 Android 開發
本文是上一篇的延续,阅读前建议先看第一部分。上一篇中,我们通过替换 Component 成功"欺骗"了 AMS,拿到了启动一个 Activity 所必需的资源,但还没有把这些资源真正转移到插件的 Activity 之下。这一节就来解决这个问题。
所有答案都来自对源码的分析,因此我们继续跟踪源码,看看 AMS 是如何把资源关联到某个 Activity 上的,如此才有可能把这些资源转移到插件的 Activity 之下。
上一篇我们分析到了 startActivityLocked 函数,在获取到启动信息与目标 Activity 信息后,转入 startActivityUncheckedLocked:
final int startActivityUncheckedLocked(ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, Bundle options, TaskRecord inTask) {
// 判断是否需重新创建任务栈,本例中 newTask 一直为 false
boolean newTask = false;
boolean keepCurTransition = false;
// 是否应视为新任务的处理逻辑……
// 调用 ActivityStack 的成员函数
targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
return ActivityManager.START_SUCCESS;
}
随后调用的是 ActivityStack 的 startActivityLocked 方法:
final void startActivityLocked(ActivityRecord r, boolean newTask, boolean doResume,
boolean keepCurTransition, Bundle options) {
if (!newTask) {
// 在已有任务中查找位置……
for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
task = mTaskHistory.get(taskNdx);
if (task.getTopActivity() == null) continue;
if (task == r.task) {
if (!startIt) {
task.addActivityToTop(r);
r.putInHistory();
mWindowManager.addAppToken(...);
ActivityOptions.abort(options);
return;
}
break;
} else if (task.numFullscreen > 0) {
startIt = false;
}
}
}
// 把要启动的 Activity 压入活动栈
task.addActivityToTop(r);
task.setFrontOfTask();
if (doResume) {
mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
}
}
这个函数做的事情很简单:把要启动的 Activity 压到活动栈栈顶。这印证了我们之前的猜想——AMS 解析 Intent 获得 ActivityRecord,而 ActivityRecord 用来表示一个 Activity;由于代码中是显式启动,替换 ComponentName 即可。
接着转入 StackSupervisor 查看 resumeTopActivitiesLocked:

先判断是否是最前面一个任务栈(很好理解,因为手机可能同时开着 QQ、微信、微博等多个应用,各自对应多个活动栈),是的话准备响应它。
stack.resumeTopActivityLocked:

最终都转发到 resumeTopActivityInnerLocked:
final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
// 需要先暂停当前 Activity,才能恢复栈顶的 Activity
boolean dontWaitForPause = (next.info.flags & ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
if (mResumedActivity != null) {
pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
}
return true;
}
确认无误后调用 startPausingLocked:
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
boolean resuming, boolean dontWait) {
if (prev.app != null && prev.app.thread != null) {
try {
// prev.app.thread 返回一个 IApplicationThread
prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
userLeaving, prev.configChangeFlags, dontWait);
} catch (Exception e) { ... }
}
...
}
prev.app.thread 返回一个 IApplicationThread,它通知 UI 线程可以结束当前响应的 Activity 了,因为要开启新的 Activity。
在本例中就是:

这里 prev.appToken 是一个 IBinder 对象,其余都是 boolean 和 Configuration 类型。不难得出:AMS 区分是哪个 Activity,正是通过这个 IBinder 对象(Token 是 IBinder 的实现类)!

为验证猜想,继续读源码:

Handler 中的处理代码:

IBinder 被保存在 Message 的 obj 中,之后调用 handlePauseActivity:

// mActivities 是一个 map,通过 IBinder 映射 ActivityClientRecord! final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
这里通过 IBinder 找到要停止的类。看来 AMS 正是通过这个 IBinder 来区分要操作的 Activity!那么,只要我们能替换掉本该给 StubActivity 的 IBinder,PluginActivity 是不是就名正言顺地获得了 AMS 的认可,间接也就获得了生命周期呢?
之后的操作:

回到 AMS 中:
@Override
public final void activityPaused(IBinder token) {
final long origId = Binder.clearCallingIdentity();
synchronized (this) {
// 通过这个 IBinder 找到任务栈
ActivityStack stack = ActivityRecord.getStackLocked(token);
if (stack != null) {
stack.activityPausedLocked(token, false);
}
}
Binder.restoreCallingIdentity(origId);
}
接着是 ActivityStack 的 activityPausedLocked:
final void activityPausedLocked(IBinder token, boolean timeout) {
final ActivityRecord r = isInStackLocked(token);
if (r != null) {
mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
if (mPausingActivity == r) {
completePauseLocked(true);
} else {
EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE, ...);
}
}
}
由于篇幅限制,我们只分析到这里。之后 AMS 就准备真正启动 Activity 了:
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
// 回调到 UI 线程,第二个参数就是之前分析的 IBinder
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info,
new Configuration(mService.mConfiguration), r.compat,
r.launchedFromPackage, r.task.voiceInteractor,
app.repProcState, r.icicle, r.persistentState,
results, newIntents, !andResume,
mService.isNextTransitionForward(), profilerInfo);
return true;
}
这里回调 UI 线程开始真正启动 Activity。
ActivityThread.java:

和之前一样,把 AMS 返回的资源封装到 ActivityClientRecord 后发送 message,并把资源存储在 Message 的 obj 中。
之后进入 H 的处理函数:

它的 handleMessage 函数:

这里补充一个小知识:Handler 调用 handleMessage 时会先调用 dispatchMessage 来分发消息。从源码可见,如果 Message 自身有 callback,就调用 Message 自己的 callback;否则看 Handler 本身的 mCallback,若不为空则调用它,返回 true 就直接结束,否则才调用我们重写的 handleMessage。

思路由此而来:我们先 hook H 这个类的 mCallback 域,替换成自己的 callback。当检测到处理的消息是针对 StubActivity 时,取出原来启动插件的 Intent,然后替换 Component(与原来逆向的过程相反)。主要代码如下:
public class HookApplication extends Application {
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
try {
// 获得 ActivityManagerNative
Class<?> serviceManagerClz = Class.forName("android.app.ActivityManagerNative", false, getClassLoader());
Method getDefaultMethod = serviceManagerClz.getDeclaredMethod("getDefault");
Object rawIActivityManagerInterface = getDefaultMethod.invoke(null);
// 我们自己的 Hook 对象
Object hookIActivityManagerInterface = Proxy.newProxyInstance(
getClassLoader(),
new Class[]{Class.forName("android.app.IActivityManager", false, getClassLoader())},
new AMSHook(rawIActivityManagerInterface));
// 反射 ActivityManagerNative 的 gDefault 域
Field gDefaultField = serviceManagerClz.getDeclaredField("gDefault");
gDefaultField.setAccessible(true);
Object gDefaultObject = gDefaultField.get(null);
// 它的类型是 Singleton
Class<?> singletonClz = Class.forName("android.util.Singleton", false, getClassLoader());
Field mInstanceField = singletonClz.getDeclaredField("mInstance");
mInstanceField.setAccessible(true);
mInstanceField.set(gDefaultObject, hookIActivityManagerInterface);
// hook ActivityThread 的 mH 的 mCallback
Class<?> activityThreadClz = Class.forName("android.app.ActivityThread", false, getClassLoader());
Method method = activityThreadClz.getDeclaredMethod("currentActivityThread");
Object activityThreadObject = method.invoke(null);
Field mHField = activityThreadClz.getDeclaredField("mH");
mHField.setAccessible(true);
Object mHObject = mHField.get(activityThreadObject);
Field handlerCallbackField = Handler.class.getDeclaredField("mCallback");
handlerCallbackField.setAccessible(true);
Object callbackObject = handlerCallbackField.get(mHObject);
Object hookHObject = new MessageHook(callbackObject, getClassLoader());
handlerCallbackField.set(mHObject, hookHObject);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class MessageHook implements Handler.Callback {
private Handler.Callback m_base;
private static final int LAUNCH_ACTIVITY = 100;
private Field m_intentField;
public MessageHook(Object base, ClassLoader classLoader) throws Exception {
m_base = (Handler.Callback) base;
Class<?> activityClientRecordClz = Class.forName("android.app.ActivityThread$ActivityClientRecord", false, classLoader);
m_intentField = activityClientRecordClz.getDeclaredField("intent");
m_intentField.setAccessible(true);
}
@Override
public boolean handleMessage(Message msg) {
if (msg.what == LAUNCH_ACTIVITY) {
try {
Intent intent = (Intent) m_intentField.get(msg.obj);
ComponentName componentName = intent.getComponent();
if (componentName != null && componentName.getClassName().equals(StubActivity.class.getCanonicalName())) {
Intent raw = intent.getParcelableExtra(Constant.EXTRA_RAW_INTENT);
intent.setComponent(raw.getComponent());
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return m_base != null && m_base.handleMessage(msg);
}
}
public class AMSHook implements InvocationHandler {
private Object m_base;
public AMSHook(Object base) { m_base = base; }
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("startActivity".equals(method.getName())) {
Intent raw = null;
final int size = (args == null ? 0 : args.length);
int i = 0;
for (; i < size; ++i) {
if (args[i] instanceof Intent) { raw = (Intent) args[i]; break; }
}
if (raw.getBooleanExtra(Constant.EXTRA_INVOKE_PLUGIN, false)) {
ComponentName componentName = raw.getComponent();
Intent intent = new Intent();
intent.setComponent(new ComponentName(componentName.getPackageName(), StubActivity.class.getCanonicalName()));
intent.putExtra(Constant.EXTRA_RAW_INTENT, raw);
args[i] = intent;
}
}
return method.invoke(m_base, args);
}
}
效果:

最后解释一下如何 hook AMS。参考之前分析过的 hook 系统服务的例子:启动 Activity 时会调用相关方法,而 gDefault 是一个 Singleton 对象,其具体实现中持有 mInstance。因此只要 hook 住 mInstance,把它替换成我们的代理对象,再拦截其中的 startActivity 方法,检测是否是启动插件 Activity 的标志,替换其中的 Component 即可:
// 看下是否是启动插件中的 activity
if (raw.getBooleanExtra(Constant.EXTRA_INVOKE_PLUGIN, false)) {
ComponentName componentName = raw.getComponent();
Intent intent = new Intent();
intent.setComponent(new ComponentName(componentName.getPackageName(), StubActivity.class.getCanonicalName()));
intent.putExtra(Constant.EXTRA_RAW_INTENT, raw);
args[i] = intent;
}
Fragment 的兩種添加方式:XML 靜態聲明與代碼動態加載
Fragment 的兩種添加方式:XML 靜態聲明與代碼動態加載 Fragment 可以理解為 Activity 界面中的一個「行為單元」或界面片段。借助 Fragmen
資料結構入門:符號表是什麼,以及它為何重要
定義 符號表(Symbol Table)是一種儲存鍵值對的資料結構,只需支援兩個基本操作: 插入(put):把一組新的鍵值對存進表中。查找(get):依給定的鍵取出對應的
Android 全局崩潰捕獲實戰:用 UncaughtExceptionHandler 收集線上異常
Android 全局崩潰捕獲實戰:用 UncaughtExceptionHandler 收集線上異常 開發過程中最惱人的莫過於應用突然閃退回到桌面,而且往往不知道它什麼時
Android 內存分析工具入門:Memory Monitor、Heap Viewer 與 Allocation Tracker
Heap Viewer、Memory Monitor 與 Allocation Tracker 都是用來「視覺化」你的 App 內存使用情况的輔助工具,三者各有側重,搭配