Why to extend an Application class?

2019-01-02 16:50发布

Why to extend an Application class?

What is in it for me?

Why would you do that?

I read that it can be used to declare global variables, is that all or are there any other applications?

13条回答
泪湿衣
2楼-- · 2019-01-02 17:55

I see that this question is missing an answer. I extend Application because I use Bill Pugh Singleton implementation (see reference) and some of my singletons need context. The Application class looks like this:

public class MyApplication extends Application {

    private static final String TAG = MyApplication.class.getSimpleName();

    private static MyApplication sInstance;

    @Contract(pure = true)
    @Nullable
    public static Context getAppContext() {
        return sInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate() called");
        sInstance = this;
    }
}

And the singletons look like this:

public class DataManager {

    private static final String TAG = DataManager.class.getSimpleName();

    @Contract(pure = true)
    public static DataManager getInstance() {
        return InstanceHolder.INSTANCE;
    }

    private DataManager() {
        doStuffRequiringContext(MyApplication.getAppContext());
    }

    private static final class InstanceHolder {
        @SuppressLint("StaticFieldLeak")
        private static final DataManager INSTANCE = new DataManager();
    }
}

This way I don't need to have a context every time I'm using a singleton and get lazy synchronized initialization with minimal amount of code.

Tip: updating Android Studio singleton template saves a lot of time.

查看更多
登录 后发表回答