静态上下文警告 [英] Static Context Warning

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

问题描述

当类包含静态Context对象时,Android Studio现在显示警告.它说这会导致内存泄漏.但是,我注意到这也是在android库中完成的.例如,LocalBroacastManager类有一个静态实例,它包含一个context对象.

Android Studio now displays a warning when a class contains a static Context object. It says this causes a memory leak. However, I have noticed this is also done in android libraries. For instance, the LocalBroacastManager class has a static instance and it contains a context object.

那作为内存泄漏有多严重?

So how bad is this as a memory leak?

我有一个单例地理围栏类,该类在后台运行,并将boolean保存到sharedPreferences,以指示用户是否在地理围栏中.要保存首选项,我需要一个context对象,但是由于该方法是一个覆盖的方法,因此我无法传递上下文对象.

I have a singleton geofencing class that runs in the background and saves a boolean to sharedPreferences indicating if the user is in the geofence or not. To save the preferences I need a context object, but since the method is an overridden method, I have no way of passing a context object in.

如何在没有context实例变量的情况下完成此操作?

How can this be accomplished without a context instance variable?

推荐答案

这是您可能遇到的最糟糕的情况.假设您有一个Activity,并将其存储为静态Context.除非您在活动结束时将其清空,否则您现在已经泄漏了整个活动.这意味着活动包含的每个变量都将泄漏,包括整个视图层次结构.它基本上阻止了上下文中的任何内容释放.

Its about the worst you can have. Lets say that you have an Activity, and store that as a static Context. Unless you null it out when the activity finishes, you now have leaked a whole Activity. That means every variable that the activity holds is leaked, including the entire view hierarchy. Its basically preventing anything in that Context from freeing up.

最好的办法不是存储上下文,而是将其作为参数传递给需要它的函数.如果必须存储上下文,请不要将其设为静态.只要活动完成后框架中没有任何东西继续持有对该对象的引用,那么非静态变量就不会泄漏它.

The best thing to do is not to store a Context, but instead to pass it in as a parameter to functions that need it. If you must store a Context, do not make it static. A non-static variable won't leak it so long as nothing in the framework continues to hold a reference to the object after the activity is finished.

如果绝对必须使用静态上下文,则将其设置为应用程序上下文.该代码在您的应用程序的整个长度内都是有效的,因此它不会真正被泄漏.

If you absolutely must use a static Context, make it the Application context. That one is valid over the length of your app, so it can't really be leaked.

这篇关于静态上下文警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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