如果您的应用程序要向公众发布,并且您的配置中有敏感数据,例如 API 密钥或密码,我建议使用 secure-preferences 而不是 SharedPreferences,因为最终使用 SharedPreferences以明文形式存储在 XML 中,在有根手机上,应用程序很容易访问其他人的共享首选项。
默认情况下,它不是防弹安全(实际上它更像
偏好的混淆),但对于渐进式来说,这是一个快速的胜利
让你的安卓应用更安全。例如,它会阻止用户
植根设备可以轻松修改您应用的共享首选项。 (link)
我会建议其他一些方法:
*方法一:使用带有Properties的.properties文件
优点:
- 无论您使用什么 IDE,都可以轻松编辑
- 更安全:因为它是使用您的应用编译的
- 如果你使用Build variants/Flavors,可以很容易地被覆盖
- 你也可以写在config里
缺点:
- 您需要上下文
- 您也可以在配置中写入(是的,它也可以是一个骗局)
- (还有别的吗?)
首先,创建一个配置文件: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");
当然,这可以优化为读取配置文件一次并获取所有值。
方法二:使用AndroidManifest.xml meta-data元素:
就我个人而言,我从来没有使用过这种方法,因为它看起来不太灵活。
在您的 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:在Flavor中使用buildConfigField:
我在 Android 官方文档/培训中没有找到这个,但是this blog article 非常有用。
基本上设置一个项目的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;