public void hookSystemHandler() {
try {
Class<?> forName = Class.forName("android.app.ActivityThread");
Field currentActivityThread = forName.getDeclaredField("sCurrentActivityThread");
currentActivityThread.setAccessible(true);
Object activityThreadValue = currentActivityThread.get(null);//程序的入口
Field handlerField = forName.getDeclaredField("mH");
handlerField.setAccessible(true);
Handler handlerObject = (Handler) handlerField.get(activityThreadValue);
Field callbackField = Handler.class.getDeclaredField("mCallback");
callbackField.setAccessible(true); //防止私有
callbackField.set(handlerObject,new ActivityThreadHandlerCallback(handlerObject));
} catch (Exception ex) {
ex.printStackTrace();
}
}
class ActivityThreadHandlerCallback implements Handler.Callback{
Handler handler;
public ActivityThreadHandlerCallback(Handler handler) {
this.handler = handler;
}
@Override
public boolean handleMessage(Message message) {
Log.i("INFO","message callback");
//这里替换回之前的intent
if (message.what == 100){
Log.i("INFO","lauchActivity");
handleLaunchActivity(message);
}
handler.handleMessage(message);
return true;
}
private void handleLaunchActivity(Message message) {
Object obj = message.obj; //ActivityClientRecord
try {
//不能强转 framwork层
Field intentField = obj.getClass().getDeclaredField("intent");
intentField.setAccessible(true);
Intent proxyIntent = (Intent) intentField.get(obj);
Intent realIntent = proxyIntent.getParcelableExtra("oldIntent");
if (realIntent != null){
//代理意图替换成真实意图
proxyIntent.setComponent(realIntent.getComponent());
}
}catch (Exception e){
e.printStackTrace();
}
}
}