2016-11-30 74 views
-3

我的應用程序中有一項服務始終在運行,但全局靜態變量似乎在手機閒置一段時間後重置(可能應用程序正在關閉)。請讓我知道存儲重複使用價值的最佳方式,可能一次2-5分鐘。Android - 正確的方式來存儲重複使用的值?

如果在2-5分鐘內訪問一次,使用SharedPreference會導致高開銷嗎?

感謝您的幫助。

+0

如果你有更多的價值,然後存儲在數據庫,否則會話是足夠的 – Vadivel

+0

只需要存儲一個值。使用SharedPreference非常頻繁地訪問該值(一分鐘內)會導致很高的開銷? –

+0

不,您可以使用SharedPreference – Vadivel

回答

1

SharedPreference是最佳選擇。

public class AppPreference { 
public static final String APP_NAME_KEY= "your_app_name"; 
public static final String SAMPLE_KEY = "sample"; 

public SharedPreferences preferences; 
private SharedPreferences.Editor editor; 

private String sample; 

public AppPreference(Context context) { 
     preferences = context.getSharedPreferences(APP_NAME_KEY, Context.MODE_PRIVATE); 
     editor = preferences.edit(); 
    } 

public void setSample(String sample) { 
    this.sample= sample; 
    editor.putString(SAMPLE_KEY , this.sample); 
    editor.commit(); 
} 

public String getSample() { 
     return preferences.getString(SAMPLE_KEY, null); 
    } 
} 

您可以根據您的要求使用Integer,Float,布爾值。

相關問題