App 类中的静态上下文 - 内存泄漏 [英] Static context in App class - memory leak

查看:55
本文介绍了App 类中的静态上下文 - 内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了能够在我的应用程序中的任何地方获取应用程序上下文,我创建了这样的应用程序类:

To be able to get app context anywhere in my app, I created App class like this:

public class App extends Application
{
    private static Context mContext;

    public static Context getContext()
    {
        return mContext;
    }


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

    }
}

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

It works and also it's used in many places in my app where I need to use context (for example, to load resources) and I am not able to inject any other context to use.

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

However, Android Studio throws warning this approach (static context fields) causes memory leak.

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

Do you have any idea how to avoid static context field, but get similar functionality?

推荐答案

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

Never place static Context in your application since it will cause unexcepted memory leaks, however if you still want to use static Context in your application you can wrap the context in a WeakReference so change

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/弱引用

if you want to research more about WeakRef use the link below, https://developer.android.com/reference/java/lang/ref/WeakReference

这篇关于App 类中的静态上下文 - 内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆