0 引入包
根目录下的build.gradle中,dependencies添加以下两个依赖,很多网上文章说只需依赖第一个,运行时候会报错:
classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:1.1.0'
classpath 'org.aspectj:aspectjtools:1.8.14'
然后再主项目或者库的build.gradle中增加AspectJ的依赖:
compile 'org.aspectj:aspectjrt:1.8.14'
同时在build.gradle中加入AspectJX模块:
apply plugin: 'android-aspectjx'
1 定义切面类
TestAnnoAspect
@Aspect
public class TestAnnoAspect {
private static final String TAG = "jack";
@Before("execution(* com.jack.aop.MainActivity.onCreate(..))")
public void onActivityMethodBefore(JoinPoint joinPoint) throws Throwable {
String key = joinPoint.getSignature().toString();
Log.d(TAG, "onActivityMethodBefore: " + key);
}
@After("execution(* android.app.Activity.onResume(..))")
public void onActivityMethodafter(JoinPoint joinPoint) throws Throwable {
String key = joinPoint.getSignature().toString();
Log.d(TAG, "onActivityMethodafter: " + key);
}
}
在类的最开始,我们使用@Aspect注解来定义这样一个AspectJ文件,编译器在编译的时候,就会自动去解析,并不需要主动去调用AspectJ类里面的代码。
MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
经过编译后:MainActivity.class
public class MainActivity
extends AppCompatActivity
{
private static final JoinPoint.StaticPart ajc$tjp_0;
private static final JoinPoint.StaticPart ajc$tjp_1;
private static void ajc$preClinit()
{
Factory localFactory = new Factory("MainActivity.java", MainActivity.class);
ajc$tjp_0 = localFactory.makeSJP("method-execution",
localFactory.makeMethodSig("4", "onCreate", "com.jack.aop.MainActivity",
"android.os.Bundle", "savedInstanceState", "", "void"), 11);
ajc$tjp_1 = localFactory.makeSJP("method-execution",
localFactory.makeMethodSig("4", "onResume", "com.jack.aop.MainActivity",
"", "", "", "void"), 18);
}
protected void onCreate(Bundle savedInstanceState)
{
Bundle localBundle = savedInstanceState;
JoinPoint localJoinPoint = Factory.makeJP(ajc$tjp_0, this, this, localBundle);
TestAnnoAspect.aspectOf().onActivityMethodBefore(localJoinPoint);
super.onCreate(savedInstanceState);
setContentView(2131296283);
}
protected void onResume()
{
JoinPoint localJoinPoint = Factory.makeJP(ajc$tjp_1, this, this);
try
{
super.onResume();
}
catch (Throwable localThrowable)
{
TestAnnoAspect.aspectOf().onActivityMethodafter(localJoinPoint);throw localThrowable;
}
TestAnnoAspect.aspectOf().onActivityMethodafter(localJoinPoint);
}
static {}
}
可以看到在onCreate和onResume中插入了代码。
完毕