使用 sets 调用构造函数 class 并从 asyncTask 获取 sharedpreferences(无法传递上下文)

Calling constructor class with sets and gets sharedpreferences from an asyncTask (can't pass context)

我正在构造函数中获取和设置 sharedPreferences class

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();
}

但是我是从异步任务(它使用 Wea​​kReference 上下文,以防止内存泄漏)调用它

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";
}

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

如何使用上下文调用我的构造函数 class 而不会导致内存泄漏?

您需要在弱引用实例上使用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";
}