Android: get active, current or foreground Activity

13 Jul

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:


Visit this gist to get the source code.

Leave a comment

Posted by on July 13, 2016 in Android, Programming


Tags: , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: