3
我正在構建一個類來處理應用程序共享首選項。我想讓它從項目的所有部分訪問單例。我不能使用常規的getInstance方法,因爲我需要傳遞該類的上下文才能正常工作。我想在MainActivity.java中傳遞一個上下文,並且不停地在它上面。會不會有內存泄漏?帶上下文作爲變量的單身 - 內存泄漏?
這是我目前的解決方案:
public class LocalStorage {
private Context context;
private static LocalStorage instance = null;
protected LocalStorage() {
// Exists only to defeat instantiation.
}
public static LocalStorage getInstance() {
if(instance == null) {
instance = new LocalStorage();
}
return instance;
}
public static LocalStorage getInstance(Context _context) {
LocalStorage localStorage = getInstance();
localStorage.context = _context.getApplicationContext();
return localStorage;
}
private SharedPreferences sharedPreferences() {
return context.getSharedPreferences("mySettings", Context.MODE_PRIVATE);
}
....
謝謝。關於代碼示例,這意味着我總是需要爲getInstance提供一個上下文。我只想做一次。 – Guy
我明白了。只做一次的問題是,你必須保證代碼在任何其他沒有提供Context的'getInstance()'調用之前先運行,否則你將在沒有'Context'的情況下初始化你的單例。這是容易出錯的。當你需要訪問'Context'時通常不會有問題。尤其是應用程序上下文 –
如何在應用程序類的onCreate方法上設置單例的上下文?它不會總是首先運行嗎?有沒有這樣做的警告? – Guy