使用静态类AppContext是个好主意吗?

时间:2016-03-29 19:40:48

标签: java android

我在github project课程中找到了一个:

public class AppContext {

    private static Context sContext;
    private static Application sApplication;

    public static Application getApplication() {
        if (sApplication == null) {
            throw new IllegalStateException("AppContext.setApplication was not called in Application.onCreate() method. " +
                    "Please inherit your application from the com.blandware.android.atleap.BaseApplication class.");
        }

        return sApplication;
    }

    public static void setApplication(Application application) {
        sApplication = application;
    }

    public static Context getContext() {
        if (sContext == null) {
            throw new IllegalStateException("AppContext.setContext was not called in Application.onCreate() method. " +
                    "Please inherit your application from the com.blandware.android.atleap.BaseApplication class.");
        }

        return sContext;
    }


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

它接缝创建,不需要更多的传递上下文到静态功能等。但我担心内存泄漏。 AppContext可以做到吗?当我在活动上下文或视图时使用Aplication上下文?

1 个答案:

答案 0 :(得分:3)

Application对象无法泄露。每个应用程序始终只有一个Application对象。看起来作者只是使用这个类,以便在没有其他Context可用于调用getApplicationContext()来获取Application对象的地方轻松访问。

另一方面,上下文可以是一个活动或一个服务,而那些确实不应该存储在其生命周期之外。您将不得不仔细查看这里存储的Context对象,以确定是否存在泄漏。