[android] get Context in non-Activity class

In an android Application, is there any way to get the context in android in a non-activity class if the activity class name is known?

This question is related to android android-context

The answer is


If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);