Storing configs in android

若如初见. 提交于 2019-12-11 05:47:10

问题


I'm trying to work out where the best place to put config type data is. At the moment everything is hardcoded in java e.g API endpoint URLs, API keys etc. Can they just go in strings resources? or in a static class?

side note - is it safe to keep API keys like this?


回答1:


There are some options to use:

1.Static class (something like Config.java) or singleton object. For example:

public enum Config {
    INSTANCE;

    public static final String CLOUD_ID = "8888888888";
}

2.String resources (strings.xml or separate string file like api.xml). For example:

 <string name="google_cloud_message_register_id" translatable="false">8888888888</string>

3.Integer resources (xml file like integers.xml). For example:

<resources>
    <integer name="category_id">777</integer>
</resources>

4.SharedPreferences storage. For example:

mSharedPreferences.edit().putString(AUTH_EMAIL_KEY, authEmail).commit(); // to save
mSharedPreferences.getString(AUTH_EMAIL_KEY, null); // to get

5.External storage (i.e. files)

6.SQLite database

7.Gradle build script configuration. For example:

// in build.gradle
buildTypes {
    release {
        buildConfigField "String", "API", "\"https://api.com/api/\""
    }
}

BuildConfig.API // access in Java code

For API endpoint URLs, public API keys etc. I prefer to use Gradle build script configuration. It's very flexible and different values can be used with various build types.

Encrypted SQLite table can be used to store delicate private data but the best way to save private data is load them from protected external server, I think.




回答2:


SharedPreferences might be your best bet to store configurations for your app.

It is basically designed for this kind of data storage. Although it is accessible by other apps with superuser privileges on a rooted device, so you might want to encrypt sensitive data.

On an unrooted device it can only be accessed by the app, it is safe on code level.

Check out the developer's guide.

If your configuration never changes, a static class could also be an option.



来源:https://stackoverflow.com/questions/37883186/storing-configs-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!