我的应用程序中有 10 个 URL,目前是硬编码的。我想将其外部化并放入文件中,以便我的应用程序可以读取它。
这样做的最佳方法是什么?
private String appURL = "http://..."
private String storeURL = "http://..."
private String someURL = "http://..."
注意:我永远不会在我的应用程序中写出这个文件。我希望开发人员能够打开该文件,并在必要时更改 URL。
最佳答案
在 Android 应用程序中外部化字符串的最简单方法是使用字符串资源。在 res/values
文件夹中创建文件 uris.xml
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="appUrl">http://...</string>
<string name="storeUrl">http://...</string>
<!-- etc /-->
</resources>
然后您可以通过以下方式访问字符串:
String appUrl = getString(R.string.appUrl);
String storeUrl = getString(R.string.storeUrl);
//..etc
getString()
是Context
类的一个方法。还要记住,您应该等到 Context
被初始化,然后才能开始访问其资源。因此,调用 getString()
的时间不能早于 Activity
或 Application
的 onCreate()
方法。
关于java - 外部化 URL 的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4156715/