Android: get active, current or foreground Activity


In our recent Android App development, we developed many static utility functions, which needs a Context as the argument:

public static void func1(Context context, …)
public static void func2(Context context, …)
public static void func3(Context context, …)

public static void funcN(Context context, …)

This is very cumbersome. We would like to refactor these utility functions into functions without the context argument/ A natural idea to pass in the application context at the very beginning, e.g. Application.onCreate() function, but not in all cases, can we use the application context. For instance, when you create a dialog or toast window, we need to use Activity as the context. So here comes the function that works:

image

Visit this gist to get the source code.