简体   繁体   English

如何静态获取非活动类的当前活动上下文

[英]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. 我已经尝试创建一个新的应用程序(MyApplication扩展应用程序),作为一个新的应用程序和主要的应用程序,并没有工作。 Any suggestions? 有什么建议?

Current Code: 现行代码:

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

The cleaner way to do it is to pass in a Context to each method. 更简洁的方法是将Context传递给每个方法。 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. 当然,如果你真的需要静态引用它,你可以在SharedFunctions类中保留一个静态成员并为每个Activity设置它。

onResume() and onPause() may be good places to set/clear it, but depending on your needs, you might want to change it. onResume()onPause()可能是设置/清除它的好地方,但根据您的需要,您可能想要更改它。 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);
}

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) 之后,您必须将此类添加到应用程序中的字段名称(Manifest)

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

As a result you can call MyApplication.getContext() anywhere in your application and get the context. 因此,您可以在应用程序的任何位置调用MyApplication.getContext()并获取上下文。

hope, I help you. 希望,我帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM