這很含糊。我不認爲有任何規定的「最佳方式」來實現常數值。
這樣說,這裏是在黑暗中了幾槍:
方法1 ......一個標準,著名的類與常量值public static
領域
public final class Constants {
private Constants() { throw new AssertionError(); }
public static final String VALUE_1 = "some constant value";
public static final int VALUE_2 = 43;
}
方法2 ...如果您有衆所周知的值組合,您可以使用一個衆所周知的枚舉類型,並使用常量值和相關訪問器對這些值進行初始化
public enum Constants {
TYPE_1 ("some constant value", 32),
TYPE_2 ("another constant value", 43);
private String stringConstant;
private int integerConstant;
protected Constants(String stringConstant, integerConstant) {
this.stringConstant = stringConstant;
this.integerConstant = integerConstant;
}
public String stringConstant() { return this.stringConstant; }
public int integerConstant() { return this.integerConstant; }
}
方法3 ...你可以利用搖籃構建系統寫常量值生成的BuildConfig
類
(在應用程序的的build.gradle)
android {
...
buildConfigField 'String', 'TYPE_1', '"some constant value"'
...
}
構建您的項目會在您的應用生成的BuildConfig類中產生一個名爲TYPE_1
的public static
字段。
來源
2015-12-18 20:59:56
hsl
「常量」是內存中的預加載值,一旦聲明後就不能修改(不應該)。你所說的看起來像你想從互聯網上推新的常量(比如更新應用程序),但是它打敗了常量的目的。考慮使用'SharedPreferences'或'sqlite',以便用戶可以將這些下載的值保存到android內部存儲中。 –
你絕對不希望強迫用戶更新你的應用程序的東西。相反,您應該讓應用程序將遠程調用發送給任何源定期發佈這些值(啓動時,按預定的時間間隔等)。取決於你選擇這樣做的頻率,你可能還想將這些值本地存儲在Shared Preferences或DB中(如@Saehun Sean Oh提到的) – hsl
非常感謝.... – Arturkamz