1

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

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

1 回答 1

3

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

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

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

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

于 2019-02-11T15:19:39.783 回答