Business Objects中的应用程序上下文

时间:2014-09-17 17:16:02

标签: java android

所以我有一个Configuration类看起来像这样:

public class Configuration {
    private static Configuration global;

    private String authToken;
    //other config fields

    public Configuration(Properties props) {
        //get config options from properties
    }

    public static getConfiguration() {
        if (global == null) {
            Properties props = ....
            global = new Configuration(props);
        }

        return global;
    }

    public String getAuthToken() {
        if (authToken == null) {

            //NEED context here
            FileInputStream fis = context.openFileInput("fileName");
            //read in auth token
        }

        return authToken;
    }
}

评论中说明的问题是我需要一个Context对象来读取android的内部存储机制。似乎我唯一的选择是将Context作为参数传递给getAuthToken:

public String getAuthToken(Context c)

但这意味着我需要将Context实例传递给我的业务对象,以便他们可以调用此方法,例如。

public class BusinessObject {

    private Context c;

    public BusinessObject(Context c) {
        this.c = c;
    }

    public void doSomething() {
        String authToken = Configuration.getConfiguration().getAuthToken(this.c);
    }
}

这看起来真的很乱。有没有更好的方法来解决这个问题?

编辑:

作为某些上下文的注释(没有双关语),我基本上是尝试为API存储身份验证令牌,这样如果令牌没有,每次启动应用时我都不需要询问用户的凭据尚未过期。

2 个答案:

答案 0 :(得分:2)

添加一个Context静态成员,您可以通过应用启动代码中的某个位置(例如您的发布活动的onCreate())进行初始化。隐藏Activity上下文是不安全的,但隐藏Application上下文是安全的。初始化可能如下所示:

public class Configuration {
    private static Context sContext;

    public static void initContext(Context context) {
        if (sContext == null) {
            sContext = context.getApplicationContext();
        }
    }    

    . . .
}

答案 1 :(得分:0)

您可以创建Application扩展android.app.Application,使其成为单身,并在Application.getInstance().getApplicationContext()中调用Configuration.getAuthToken()

相关问题