使用上下文作为变量的单例 - 内存泄漏?

时间:2016-04-23 23:00:16

标签: java android

我正在构建一个类来处理应用程序共享首选项。我想让它从项目的所有部分访问单例。我不能使用常规的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);
    }
 ....

1 个答案:

答案 0 :(得分:10)

您不会创建泄漏,因为您只是通过调用_context来保留对应用程序上下文的引用。

如果您直接引用Activity并且该引用恰好是Context或其他getInstance(),那么您可能会创建内存泄漏。

作为旁注,这里Singleton的实现有点奇怪。我建议通过将Context传递给构造函数来删除不必要的额外public class LocalStorage { private static LocalStorage instance = null; private Context context; private LocalStorage(Context context) { this.context = context; } public synchronized static LocalStorage getInstance(Context context) { if(instance == null) { instance = new LocalStorage(context.getApplicationContext()); } return instance; } private SharedPreferences sharedPreferences() { return context.getSharedPreferences("mySettings", Context.MODE_PRIVATE); } ....

import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {GlobalService} from '../app.service';

@Injectable()
export class AuthenticationService {
    constructor(private _globals: GlobalService) {}
    constructor(private _http: Http) {}
    globals = this._globals.getGlobals()

    getAuthenticationData() {
        this._http.get(globals.apiURL)
    }
}