安卓配置文件

发布于 2024-10-19 16:23:16 字数 74 浏览 1 评论 0原文

最好的方法是什么以及如何为应用程序设置配置文件?

我希望应用程序能够查看 SD 卡上的文本文件并挑选出它需要的某些信息。

What is the 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

装纯掩盖桑 2024-10-26 16:23:16

如果您的应用程序要向公众发布,并且您的配置中有敏感数据,例如 API 密钥或密码,我建议使用 安全首选项 而不是 SharedPreferences 因为 SharedPreferences 最终以明文形式存储在 XML 中,并且在 root 后的手机上,应用程序可以很容易地访问另一个应用程序的共享首选项。

默认情况下,它不是防弹安全(实际上它更像是
混淆偏好)但这对于增量来说是一个快速的胜利
使您的 Android 应用程序更加安全。例如,它会阻止用户
获得 root 权限的设备可以轻松修改应用程序的共享首选项。 (链接

我建议其他一些方法:

*方法 1:使用一个 .properties 文件,其中包含属性

优点:

  1. 可以轻松地从您使用的任何 IDE 进行编辑
  2. 更安全:因为它是与您的应用程序一起编译的
  3. 如果您使用 构建变体/风味
  4. 你也可以在配置中写入

缺点:

  1. 你需要一个上下文
  2. 你也可以在配置中写入(是的,它也可以是一个缺点)
  3. (还有什么吗?)

首先,创建一个配置文件: res/raw/config.properties 并添加一些值:

api_url=http://url.to.api/v1/
api_key=123456

然后您可以使用如下方式轻松访问这些值:

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;
    }
}

用法:

String apiUrl = Helper.getConfigValue(this, "api_url");
String apiKey = Helper.getConfigValue(this, "api_key");

当然,这个可以优化为读取一次配置文件并获取所有值。

方法2:使用AndroidManifest.xml 元数据 element:

就我个人而言,我从来没有使用过这种方法,因为它看起来不太灵活。

在您的 AndroidManifest.xml 中,添加如下内容:

...
<application ...>
    ...

    <meta-data android:name="api_url" android:value="http://url.to.api/v1/"/>
    <meta-data android:name="api_key" android:value="123456"/>
</application>

现在是一个检索值的函数:

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;
}

用法:

String apiUrl = Helper.getMetaData(this, "api_url");
String apiKey = Helper.getMetaData(this, "api_key");

方法 3:在 风味

我在官方Android文档/培训中没有找到这个,但是这篇博客文章非常有用。

基本上设置一个项目 Flavor(例如 prod),然后在应用程序的 build.gradle 中包含类似以下内容

productFlavors {
    prod {
        buildConfigField 'String', 'API_URL', '"http://url.to.api/v1/"'
        buildConfigField 'String', 'API_KEY', '"123456"'
    }
}

String apiUrl = BuildConfig.API_URL;
String apiKey = BuildConfig.API_KEY;

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:

  1. Easy to edit from whatever IDE you are using
  2. More secure: since it is compiled with your app
  3. Can easily be overridden if you use Build variants/Flavors
  4. You can also write in the config

Cons:

  1. You need a context
  2. You can also write in the config (yes, it can also be a con)
  3. (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;
柳若烟 2024-10-26 16:23:16

您可以使用 共享首选项 来实现此目的,

有一个非常详细的指南如何在 Google Android 页面上使用共享首选项
https://developer.android.com/guide/topics/数据/data-storage.html#pref

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

或十年 2024-10-26 16:23:16

如果你想存储应用程序的首选项,Android 提供了 SharedPreferences为此。
这是官方培训资源的链接。

If you want to store the preferences of your application, Android provides SharedPreferences for this.
Here is the link to official training resource.

戈亓 2024-10-26 16:23:16

我最近遇到了这样的要求,在这里记下我是如何做到的。

该应用程序能够查看 SD 卡上的文本文件并
挑选出它需要的某些信息

要求:

  1. 配置值(score_threshold)必须在 SD 卡上可用。所以有人可以在发布 apk 后更改这些值。
  2. 配置文件必须位于 Android 硬件的“/sdcard/config.txt”中。

config.txt 文件的内容是,

score_threshold=60

创建一个实用程序类 Config.java,用于读写文本文件。

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;
    }
}

创建另一个实用程序类来写入应用程序首次执行的配置文件,
注意:应用程序必须设置SD卡读/写权限。

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);
 }

}

在您的主要活动中,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 );

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:

  1. Configuration value(score_threshold) has to be available at the sdcard. So somebody can change the values after releasing the apk.
  2. 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 );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文