2015-12-18 25 views
-1

在android中聲明常量的最佳方式。牢記這個常數每月都會有所不同。想了解如何使用Android的端點將其保存,但我不能找出我的應用程序如何下載和使用新的常量還怎麼我可以更新他們聲明頻繁變化的Android常量

public static final double inflation = 0.23; 
public static final double REP = 0.3; 

我的問題是這樣的常量將在波動幾個月的時間類似

public static final double inflation = 0.18; 
public static final double REP = 0.125; 

我的理解是,如果我聲明他們在一個Java類的用戶可能會被迫每月更新應用程序。試圖實現的是能夠及時更新這些常量。

+1

「常量」是內存中的預加載值,一旦聲明後就不能修改(不應該)。你所說的看起來像你想從互聯網上推新的常量(比如更新應用程序),但是它打敗了常量的目的。考慮使用'SharedPreferences'或'sqlite',以便用戶可以將這些下載的值保存到android內部存儲中。 –

+0

你絕對不希望強迫用戶更新你的應用程序的東西。相反,您應該讓應用程序將遠程調用發送給任何源定期發佈這些值(啓動時,按預定的時間間隔等)。取決於你選擇這樣做的頻率,你可能還想將這些值本地存儲在Shared Preferences或DB中(如@Saehun Sean Oh提到的) – hsl

+0

非常感謝.... – Arturkamz

回答

1

這很含糊。我不認爲有任何規定的「最佳方式」來實現常數值。

這樣說,這裏是在黑暗中了幾槍:

方法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_1public static字段。