1)比如普通的startActivity
InstrumentationProxy.java
public class InstrumentationProxy extends Instrumentation {
Instrumentation instrumentation;
Method execStartActivityMethod = null;
ActivityResult result = null;
//持有真正启动Activity的Instrumentation引用
public InstrumentationProxy(Instrumentation instrumentation) {
this.instrumentation = instrumentation;
}
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
try {
// 查找当前方法
execStartActivityMethod = Instrumentation.class.getDeclaredMethod("execStartActivity",
Context.class, IBinder.class, IBinder.class, Activity.class, Intent.class, int.class, Bundle.class);
execStartActivityMethod.setAccessible(true);
//可在此修改判断是否登录 然后intent.setClassName(who,"study.hank.com.androidhookdemo2.LoginActivity");
// intent.setClassName(who, "study.hank.com.androidhookdemo2.LoginActivity");
// 执行activity启动
result = (ActivityResult) execStartActivityMethod.invoke(instrumentation, who,
contextThread, token, target, intent, requestCode, options);
return result;
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
public static void replace(Activity activity) {
//通过反射获取Activity的class对象
Class<? extends Activity> aClass = Activity.class;
try {
//获取Activity的mInstrumentation属性
Field field = aClass.getDeclaredField("mInstrumentation");
//取消权限检查
field.setAccessible(true);
//获取传入的activity的mInstrumentation字段
Instrumentation mInstrumentation = (Instrumentation) field.get(activity);
//构造InstrumentationProxy,并将获取到的Activity字段传入
InstrumentationProxy instrumentationProxy = new InstrumentationProxy(mInstrumentation);
//用构造InstrumentationProxy替换掉当前Activity的mInstrumentation。
field.set(activity, instrumentationProxy);
} catch (Exception e) {
}
}
}
测试类
static class MainActivity {
InstrumentationProxy.replace(this);
startActivity(new Intent(MainActivity.this, TestActivity.class));
}