存储系统服务可以静态地导致内存泄漏?

问题描述 投票:1回答:1

我们都知道,存储上下文对象(而不是应用程序上下文等)静态是不好的做法,因为这可能会导致内存泄漏。但是你可以存储从上下文对象获得的系统服务?如ConnectivityManager

// Is this okay?
static ConnectivityMananger connectivityManager;
...
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
java android android-context
1个回答
3
投票

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

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

也许所有的系统服务使用的应用程序Context内部,但这种方法是渐进安全的,额外的方法调用的成本。

如果系统服务使用的应用程序Context,获得系统服务时,你会不会泄露一个Context。无论您通过使用该系统服务可能会有所不同泄漏别的。

© www.soinside.com 2019 - 2024. All rights reserved.