Search code examples
androidandroid-activityaopaspectjaspect

How to reference an Activity from within an Aspect


I currently have the current aspect

@Aspect
public class ActivityShowingAspect {

    private static final String POINTCUT_METHOD =
            "execution(@nz.co.kevinsahandsomedevil.android.myaccount.aspect.ActivityMustBeShowing * *(..))";

    @Pointcut(POINTCUT_METHOD)
    public void methodAnnotatedWithActivityShowing() {
    }

    @Around("methodAnnotatedWithActivityShowing()")
    public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
        Activity activity = // code to retrieve the calling activity, joinPoint.getTarget() or whatever
        Object result = null;
        if(!activity.isFinishing()) {
            result = joinPoint.proceed();
        } else {
            result = // do something else
        }
        return result;
    }

}

I'd like to know how to determine the calling Activity from within the Aspect.


Solution

  • Okay so it depends on where the method with your annotation is.

    If the annotated method is declared within an Activity implementation, then you can indeed call joinpoint.getTarget()and cast the result.

    Also you might want to update your pointcut to make sure that the method indeed is on an activity :

     execution(@nz.co.vodafone.android.myaccount.aspect.ActivityMustBeShowing * *(..)) && within(android.app.Activity+)
    

    If that's not the case then you might need to add an advice before any activity's onResume() to remember what the current activity is.