将 Context 传递给非活动类的最佳实践? [英] Best practice to pass Context to non-activity classes?

查看:40
本文介绍了将 Context 传递给非活动类的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我的第一个主要应用程序几乎已编码,我正在对我的代码进行优化.该应用程序运行良好,但我不确定将上下文传递给其他类的方式.我不想以错误的方式去做.我在 Stackoverflow 中偶然发现了关于上下文的文章和问题,这是将它传递给非活动类的正确方法.我也阅读了文档,但作为芬兰人,复杂的技术更难理解.

So, my first major application is almost coded and I'm doing optimizations on my code. The app works fine, but I'm not sure about my way of passing the context to other classes. I don't want to do it the wrong way. I stumbled upon articles and questions here in Stackoverflow about contexts and which is the right way to pass it to non-activity classes. I read the documentation as well, but being a Finn makes complicated tech speak even harder to understand.

所以,一个简单的问题.我将主要活动的上下文传递给其他(帮助程序)类的方式是否正确?如果没有,我在哪里可以阅读更多关于这些情况下的更好实践的信息.

So, a simple question. Is my way of passing my main activity's context to other (helper) classes correct? If not, where can I read more about better practice on these situations.

例如:主Activity.java

For example: MainActivity.java

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle sis){
        super(sis);
        new Helper(MyActivity.this).makeMyAppAwesome();
    }
}

Helper.java

Helper.java

public class Helper {
    Context context;
    Helper(Context ctx){
        this.context = ctx;
    }

    public void makeMyAppAwesome(){
        makeBaconAndEggsWithMeltedCheese(context);
    }
}

这样好吗?如果有人能提供一篇易于阅读的文章,并附有关于该主题的示例,那就太好了.

Is this OK? It would be nice if someone could provide an easy to read article with examples on this subject.

推荐答案

您可以使用 ContextWrapper如此处所述.

例如:

public class MyContextWrapper extends ContextWrapper {

    public MyContextWrapper(Context base) {
      super(base);
   }

    public void makeMyAppAwesome(){
        makeBaconAndEggsWithMeltedCheese(this);
    }
}

并从活动中调用这样的非活动类

And call the non activity class like this from an Activity

new MyContextWrapper(this);

这篇关于将 Context 传递给非活动类的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆