lcta0717
lcta0717

Reputation: 412

How to get the current Activity context for a non-activity class, statically

I have a non-activity class that needs to launch a new activity. Right now I just pass the current context as a parameter, but I would like to access the context statically if possible. I've already tried creating a new application (MyApplication extends Application), both as a new application and the main application, and neither worked. Any suggestions?

Current Code:

public class SharedFunctions {
    public static void doSomething(Context context){
        Intent i = new Intent(context, NextActivity.class);
        context.startActivity(i);
    }
}

Upvotes: 3

Views: 9379

Answers (2)

Geobits
Geobits

Reputation: 22342

The cleaner way to do it is to pass in a Context to each method. It's more typing, but it helps to make sure you're not leaking the reference.

Of course, if you really need static reference to it, you can just keep a static member in your SharedFunctions class and set it for each Activity.

onResume() and onPause() may be good places to set/clear it, but depending on your needs, you might want to change it. Just try not to keep references to old Activities.

public class SharedFunctions{
    private static Context context;

    public static void setContext(Context ctx){
        context = ctx;
    }

    public static void doSomething(){
        context.someContextFunction();
    }

}

In each Activity:

protected void onResume(){
    SharedFunctions.setContext(this);
}

protected void onPause(){
    SharedFunctions.setContext(null);
}

Upvotes: 3

Volodymyr Yatsykiv
Volodymyr Yatsykiv

Reputation: 3211

create this class:

public class MyApplication
    extends Application
{
    private static Context context;

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

    public static Context getContext()
    {
        return context;
    }
}

after that you must add this class to field name in application (Manifest)

<application
     android:name="yourPackageName.MyApplication"
     ........
</application >

As a result you can call MyApplication.getContext() anywhere in your application and get the context.

hope, I help you.

Upvotes: 1

Related Questions