Winks
Winks

Reputation: 417

Android - Load properties file on application launch

Is there some part of the code that is always executed on application launch, regardless of the activity, where we have access to the context?

I need api keys for my application. I store them in a .properties file in asset, and access this file from context.getRessources().getAssets() every time I need to load them.

key = getKey(getContext())

I'd like to have a static variable storing them once they have been succesfully accessed once. But since I don't know when they will be accessed for the first time, I need to do something like

if(isKeySet()){
    key = getKey();
} else {
    setKey(getContext());
}

Which is not ideal, since I still have to pass a context. If I could make sure one part of the code is always executed (with access to the context), I could load them here and every subsequent call

key = getKey();

Upvotes: 0

Views: 538

Answers (1)

code monkey
code monkey

Reputation: 2124

You can use the Android Application class. It extends Context and is a base class to store the global application state.

public class MyApplication extends Application
{
    private static MyApplication mSingleton;

    @Override
    public void onCreate()
    {
        super.onCreate();
        mSingleton = this;
    }

    public static MyApplication getInstance() {
        return mSingleton;
    }
}

In androidManifest.xml, you need to add android:name="com.X.Y.Z.MyApplication" in <application>

Now when your app launch, it will launch MyApplication.onCreate method.

After the call to super.onCreate(), you have access to getApplicationContext() and can initialise your singleton.

Upvotes: 2

Related Questions