phong phong - 6 months ago 30
Java Question

Android - How to get context from a non-activity, non-fragment static class?

I'm writing a class that contains functions of frequent use. Something like this:

public class myLib{

public static String var1="...";
public static Int var2 = 123;
public static void function1() {...}
public static void function2() {...}

}


This lib is intended to be used in android projects, and some of those static functions require access to the application context. How do I get the application context of the application calling these static function?

Answer

You can use the context from function parameter and pass the context whenever you call the function from fragment or activity.

public class myLib{

public static String var1="...";
public static Int var2 = 123;
public static void function1(Context context, ...) {...}
public static void function2() {...}

}

from Activity,

myLib.function1(this,...);