如果您确实需要将配置置于静态最终常量中,则解决方案会稍微复杂一些。此解决方案还取决于在您的清单中正确设置 debuggable,因此它并不完全是万无一失的。
我能想到的帮助您记住 debuggable 的唯一方法是使用后面提到的调试标志将初始屏幕的背景颜色更改为红色。有点傻,但会工作。
您可以将地址变量声明为 static final 并且不为其赋值:
public static final String webServiceAddress;
您可以使用以下方法获取有关您的应用程序是否设置为可调试的信息:
getApplicationInfo().flags;
这意味着当您发布应用程序并在清单中将 debuggable 设置为 false 时,您仍然需要拨动开关,但无论如何您都应该这样做以关闭您不希望用户看到的日志消息。
在您的默认活动的 onCreate 中,您可以使用它来分支并分配正确的地址。这是一个完整的例子。
//Store release configuration here, using final constants
public class ReleaseConfig {
//Don't set webServiceAddress yet
public static final String webSericeAddress;
public static boolean configSet = false;
static
{
//Set it as soon as this class is accessed
//As long as this class is first accessed after the main activity's onCreate
// runs, we can set this info in a final constant
webServiceAddress = MainActivity.configuredAddress;
}
}
public class MainActivity extends Activity {
public static String configuredAddress;
//This should be one of the first methods called in the activity
public void onCreate(Bundle savedInstanceState)
{
//Figure out if we are in debug mode or not
boolean debuggable = (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
//Save off our debug configuration
if (debuggable) configuredAddress = "the debuggable address";
else configuredAddress = "the production address";
//Access the static class, which will run it's static init block
//By the time this runs, we'll have the info we need to set the final constant
ReleaseConfig.configSet = true;
}