Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Current Activity Context in a non activity class

I have an application in android which has no. of activity. Now I needed that the context of currently running activity in a non-activity class. How can I get that.

like image 488
Mukesh Kumar Singh Avatar asked Apr 23 '13 09:04

Mukesh Kumar Singh


1 Answers

You can use Application class :

public class MyApplication extends Application {
private static Context context;
private static Activity activity;

public void onCreate() {
    super.onCreate();
    MyApplication.context = getApplicationContext();
}

public synchronized static Context getAppContext() {
    return MyApplication.context;
}

/**
 * setCurrentActivity(null) in onPause() on each activity 
 * setCurrentActivity(this) in onResume() on each activity
 * 
 */

public static void setCurrentActivity(Activity currentActivity) {
    activity = currentActivity;
}

public static Activity currentActivity() {
    return activity;
}

}
like image 117
Abdullah Avatar answered Nov 07 '22 17:11

Abdullah