Android configuration file
What is 开发者_如何学Cthe best way and how do I set up a configuration file for a application?
I want the application to be able to look into a text file on the SD card and pick out certain information that it requires.
If your application is going to be released to the public, and if you have sensitive data in your config, such as API keys or passwords, I would suggest to use secure-preferences instead of SharedPreferences since, ultimately, SharedPreferences are stored in an XML in clear text, and on a rooted phone, it is very easy for an application to access another's shared preferences.
By default it's not bullet proof security (in fact it's more like obfuscation of the preferences) but it's a quick win for incrementally making your android app more secure. For instance it'll stop users on rooted devices easily modifying your app's shared prefs. (link)
I would suggest a few other methods:
*Method 1: Use a .properties file with Properties
Pros:
- Easy to edit from whatever IDE you are using
- More secure: since it is compiled with your app
- Can easily be overridden if you use Build variants/Flavors
- You can also write in the config
Cons:
- You need a context
- You can also write in the config (yes, it can also be a con)
- (anything else?)
First, create a config file: res/raw/config.properties
and add some values:
api_url=http://url.to.api/v1/
api_key=123456
You can then easily access the values with something like this:
package some.package.name.app;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public final class Helper {
private static final String TAG = "Helper";
public static String getConfigValue(Context context, String name) {
Resources resources = context.getResources();
try {
InputStream rawResource = resources.openRawResource(R.raw.config);
Properties properties = new Properties();
properties.load(rawResource);
return properties.getProperty(name);
} catch (Resources.NotFoundException e) {
Log.e(TAG, "Unable to find the config file: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "Failed to open config file.");
}
return null;
}
}
Usage:
String apiUrl = Helper.getConfigValue(this, "api_url");
String apiKey = Helper.getConfigValue(this, "api_key");
Of course, this could be optimized to read the config file once and get all values.
Method 2: Use AndroidManifest.xml meta-data element:
Personally, I've never used this method because it doesn't seem very flexible.
In your AndroidManifest.xml
, add something like:
...
<application ...>
...
<meta-data android:name="api_url" android:value="http://url.to.api/v1/"/>
<meta-data android:name="api_key" android:value="123456"/>
</application>
Now a function to retrieve the values:
public static String getMetaData(Context context, String name) {
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
return bundle.getString(name);
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "Unable to load meta-data: " + e.getMessage());
}
return null;
}
Usage:
String apiUrl = Helper.getMetaData(this, "api_url");
String apiKey = Helper.getMetaData(this, "api_key");
Method 3: Use buildConfigField
in your Flavor:
I didn't find this in the official Android documentation/training, but this blog article is very useful.
Basically setting up a project Flavor (for example prod
) and then in your app's build.gradle
have something like:
productFlavors {
prod {
buildConfigField 'String', 'API_URL', '"http://url.to.api/v1/"'
buildConfigField 'String', 'API_KEY', '"123456"'
}
}
Usage:
String apiUrl = BuildConfig.API_URL;
String apiKey = BuildConfig.API_KEY;
You can achieve this using shared preferences
There is a very detailed guide on how to use Shared Preferences on the Google Android page https://developer.android.com/guide/topics/data/data-storage.html#pref
If you want to store the preferences of your application, Android provides SharedPreferences for this.
Here is the link to official training resource.
I met such requirement recently, noting down here, how I did it.
the application to be able to look into a text file on the sd card and pick out certain information that it requires
Requirement:
- Configuration value(score_threshold) has to be available at the sdcard. So somebody can change the values after releasing the apk.
- The config file must be available at the "/sdcard/config.txt" of the android hardware.
The config.txt file contents are,
score_threshold=60
Create a utility class Config.java, for reading and writing text file.
import android.util.Log;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
public final class Config {
private static final String TAG = Config.class.getSimpleName();
private static final String FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/config.txt";
private static Config sInstance = null;
/**
* Gets instance.
*
* @return the instance
*/
public static Config getInstance() {
if (sInstance == null) {
synchronized (Config.class) {
if (sInstance == null) {
sInstance = new Config();
}
}
}
return sInstance;
}
/**
* Write configurations values boolean.
*
* @return the boolean
*/
public boolean writeConfigurationsValues() {
try (OutputStream output = new FileOutputStream(FILE_PATH)) {
Properties prop = new Properties();
// set the properties value
prop.setProperty("score_threshold", "60");
// save properties
prop.store(output, null);
Log.i(TAG, "Configuration stored properties: " + prop);
return true;
} catch (IOException io) {
io.printStackTrace();
return false;
}
}
/**
* Get configuration value string.
*
* @param key the key
* @return the string
*/
public String getConfigurationValue(String key){
String value = "";
try (InputStream input = new FileInputStream(FILE_PATH)) {
Properties prop = new Properties();
// load a properties file
prop.load(input);
value = prop.getProperty(key);
Log.i(TAG, "Configuration stored properties value: " + value);
} catch (IOException ex) {
ex.printStackTrace();
}
return value;
}
}
Create another utility class to write the configuration file for the first time execution of the application, Note: SD card read/write permission has to be set for the application.
public class ApplicationUtils {
/**
* Sets the boolean preference value
*
* @param context the current context
* @param key the preference key
* @param value the value to be set
*/
public static void setBooleanPreferenceValue(Context context, String key, boolean value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putBoolean(key, value).commit();
}
/**
* Get the boolean preference value from the SharedPreference
*
* @param context the current context
* @param key the preference key
* @return the the preference value
*/
public static boolean getBooleanPreferenceValue(Context context, String key) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(key, false);
}
}
At your Main Activity, onCreate()
if(!ApplicationUtils.getBooleanPreferenceValue(this,"isFirstTimeExecution")){
Log.d(TAG, "First time Execution");
ApplicationUtils.setBooleanPreferenceValue(this,"isFirstTimeExecution",true);
Config.getInstance().writeConfigurationsValues();
}
// get the configuration value from the sdcard.
String thresholdScore = Config.getInstance().getConfigurationValue("score_threshold");
Log.d(TAG, "thresholdScore from config file is : "+thresholdScore );
精彩评论