Can storing a system service statically lead to memory leaks?

青春壹個敷衍的年華 提交于 2019-12-11 07:57:59

问题


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);

回答1:


I recommend using the application Context for getting such a system service:

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

Probably all system services use the application Context internally, but this approach is incrementally safer, for the cost of an additional method call.

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.



来源:https://stackoverflow.com/questions/54633492/can-storing-a-system-service-statically-lead-to-memory-leaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!