Android的 - 全局变量?全局变量、Android

2023-09-04 05:27:15 作者:死孒會狠好

我需要库存在我的应用程序的一些DATAS。 我知道我能做到这一点是这样的:

I need to stock some datas in my application. I know that i can do it like this:

类:

public class MyApplication extends Application {

    private String someVariable;

    public String getSomeVariable() {
        return someVariable;
    }

    public void setSomeVariable(String someVariable) {
        this.someVariable = someVariable;
    }
}

执行:

MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getSomeVariable();

这是工作,如果我在一个活动。

This is working if i'm in an activity.

但是,如果我在距离活动没有扩展一个类,我怎么能在我的DATAS访问?

But if i'm in a class not extended from Activity, how can I access at my datas?

在此先感谢您的帮助!

推荐答案

或许通过注射所需的所有通过构造函数或特殊的制定者一类的数据,我建议前者。 (构造器注入与Setter注入)

Perhaps by injecting all the required for a class data via constructor or special setter, I would suggest former one. (Constructor Injection vs. Setter Injection)

有更多的解决方案,如静态字段,但我个人不喜欢这种方式,因为静有时会使单元测试的有点乱。

There are more solutions like static fields but personally I do not like this approach since statics sometimes makes unit testing a bit messy.

顺便说一句,你想要什么样的变量来分享?

BTW, what kind of variables you want to share?