【问题标题】:Static context in App class - memory leakApp 类中的静态上下文 - 内存泄漏
【发布时间】:2018-10-17 06:35:54
【问题描述】:

为了能够在我的应用中的任何位置获取应用上下文,我创建了这样的 App 类:

public class App extends Application
{
    private static Context mContext;

    public static Context getContext()
    {
        return mContext;
    }


    @Override
    public void onCreate()
    {
        super.onCreate();
        mContext = this

    }
}

它可以工作,而且它在我的应用程序中的许多地方使用,我需要使用上下文(例如,加载资源)并且我无法注入任何其他上下文来使用。

但是,Android Studio 会抛出警告,这种方法(静态上下文字段)会导致内存泄漏。

你知道如何避免静态上下文字段,但获得类似的功能吗?

【问题讨论】:

标签: java android memory-leaks static


【解决方案1】:

永远不要在你的应用程序中放置静态上下文,因为它会导致无例外的内存泄漏,但是如果你仍然想在你的应用程序中使用静态上下文,你可以将上下文包装在 WeakReference 中以便更改

private static Context mContext;

private static WeakReference<Context> mContext;

并在创建时将其更改为

mContext = new WeakReference<>(Context);

最后得到上下文使用

public static Context getContext() {
    return mContext.get();
}

如果您想了解更多关于 WeakRef 的信息,请使用以下链接, https://developer.android.com/reference/java/lang/ref/WeakReference

【讨论】:

  • 在我的情况下哪个更好,使用WeakReference 或将Context 数据类型更改为App?两种灵魂都会导致停止警告。
  • App 还是会造成泄露,但是你也可以把 App 包裹在 WeakReference 里面来阻止它,做你最喜欢的事。
  • 我想我会用WeakReference 包装Context,希望对您有所帮助。实际上,我的应用程序有时会在启动画面上挂起,我怀疑是因为垃圾回收,可能是这样的内存泄漏引起的,现在我正在尝试找出任何可能的原因
【解决方案2】:

不必使用静态访问上下文,您可以使用获取上下文、获取应用程序上下文或在任何地方获取活动。 尽可能避免传递上下文。 像这样在片段中:DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getContext(), layoutManager.getOrientation());

在这种情况下(如果 OP 想要在类不承载 Context 方法的情况下使用 Context),您可以传递上下文而不将其定义为静态。 例如:

public class DashboardWalletSpinnerAdapter extends ArrayAdapter<Wallet> {

private LayoutInflater mLayoutInflater;
private static final int CLOSE = 0;
private static final int OPEN = 1;

public DashboardWalletSpinnerAdapter(Context mContext, List<Wallet> walletList) {

    super(mContext, R.layout.spinneritemclose_dashbaord, walletList);
    mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

【讨论】:

  • 这不是很准确,如果 OP 想在类不承载 Context 方法的情况下使用 Context 怎么办?
  • 是的,有时我想在活动/片段等之外获取上下文。
  • @Rab ,您可以传递上下文而不将其定义为静态
猜你喜欢
  • 2018-04-02
  • 1970-01-01
  • 2021-12-31
  • 2011-02-26
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 2018-10-17
  • 2014-08-27
相关资源
最近更新 更多