用集合调用构造函数类,并从asyncTask中获取sharedpreferences(不能传递上下文)

问题描述 投票:0回答:2

我在一个构造函数类中获取和设置sharedPreferences。

private Context context;
public NewBusiness (Context c) {
    this.context = c;
    pref = android.preference.PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    pref = context.getSharedPreferences("MyPref", 0);
    editor = pref.edit();
}
public String getLogo() {
    return pref.getString("logo", logo);
}

public void setLogo(String logo) {
    editor.putString("logo", logo);
    editor.commit();
}

但是我从一个Async任务中调用这个任务(它使用WeakReference上下文,以防止内存泄漏)。

private WeakReference<Context> contextRef;
public UploadBusiness(Context context) {
    contextRef = new WeakReference<>(context);
}
@Override
protected String doInBackground(Void... params) {

    newBusiness = new NewBusiness(contextRef); //Can´t use WeakReference<Context>
    return "Upload successful";
}

问题是,弱引用上下文不能作为上下文来传递

如何用context调用我的构造函数类而不造成内存泄漏?

android memory-leaks android-asynctask android-context weak-references
2个回答
1
投票

你需要在弱引用实例上使用get()方法来获取实际对象。类似这样的方法。

private WeakReference<Context> contextRef;
public UploadBusiness(Context context) {
    contextRef = new WeakReference<>(context);
}
@Override
protected String doInBackground(Void... params) {

    if(contextRef.get()!=null){
        newBusiness = new NewBusiness(contextRef.get());
    } 
    return "Upload successful";
}
© www.soinside.com 2019 - 2024. All rights reserved.