引入插件
classpath 'com.android.tools.build:gradle:3.1.4'
classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.8'
应用插件
apply plugin: 'android-aspectjx'
引入库
implementation 'org.aspectj:aspectjrt:1.8.14'
代码实现:
ActivityAop.java
@Aspect
public class ActivityAop {
private static final String TAG = ActivityAop.class.getSimpleName();
@Around("execution(@com.crobot.basic.activity_life_cycle.LifeCycleLog * *(..))")
public void addLifeCycleLogPointcut(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
LifeCycleLog addLog = signature.getMethod().getAnnotation(LifeCycleLog.class);
if (addLog != null) {
Object target = joinPoint.getTarget();
String className = "";
if (target != null) {
className = target.getClass().getSimpleName();
}
Log.d(TAG, "" + className + "-" + signature.getMethod().getName()+"obj:"+target.toString());
joinPoint.proceed();
// Log.d(TAG, "end execute:" + className + "-" + signature.getMethod().getName());
} else {
joinPoint.proceed();
}
}
}
BaseActivity.java
public class BaseActivity extends AppCompatActivity {
@LifeCycleLog
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@LifeCycleLog
@Override
protected void onRestart() {
super.onRestart();
}
@LifeCycleLog
@Override
protected void onStart() {
super.onStart();
}
@LifeCycleLog
@Override
protected void onResume() {
super.onResume();
}
@LifeCycleLog
@Override
protected void onPause() {
super.onPause();
}
@LifeCycleLog
@Override
protected void onStop() {
super.onStop();
}
@LifeCycleLog
@Override
protected void onDestroy() {
super.onDestroy();
}
@LifeCycleLog
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
}
实现效果