问题描述
我们都知道,静态存储上下文对象(而不是应用程序上下文)是一种不好的做法,因为它可能导致内存泄漏.但是,您可以存储从上下文对象派生的系统服务吗?如ConnectivityManager
?
We all know that storing a context object (other than the application context) statically is bad practice because it can lead to memory leaks. But can you store a system service derived from the context object? Such as ConnectivityManager
?
// Is this okay?
static ConnectivityMananger connectivityManager;
...
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
推荐答案
我建议使用应用程序Context
获得此类系统服务:
I recommend using the application Context
for getting such a system service:
connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
可能所有系统服务都在内部使用应用程序Context
,但是这种方法越来越安全,但需要额外的方法调用.
Probably all system services use the application Context
internally, but this approach is incrementally safer, for the cost of an additional method call.
如果系统服务正在使用应用程序Context
,则获取系统服务时不会泄漏Context
.通过使用系统服务是否泄漏其他内容可能会有所不同.
If the system service is using the application Context
, you will not leak a Context
when obtaining a system service. Whether you leak anything else through your use of the system service may vary.
这篇关于可以静态存储系统服务导致内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!