静态存储系统服务会导致内存泄漏吗?

Can storing a system service statically lead to memory leaks?

我们都知道静态存储上下文对象(应用程序上下文除外)是不好的做法,因为它会导致内存泄漏。但是你能存储从上下文对象派生的系统服务吗?比如ConnectivityManager?

// Is this okay?
static ConnectivityMananger connectivityManager;
...
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

我建议使用应用程序 Context 来获得这样的系统服务:

connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

可能所有系统服务都在内部使用应用程序Context,但这种方法越来越安全,因为需要额外调用方法。

如果系统服务正在使用应用程序Context,您在获取系统服务时不会泄漏Context。您是否通过使用系统服务泄漏任何其他内容可能会有所不同。