context.getSystemService()
是一个昂贵的调用吗?
即我已经构建了一个小 http 网络库(我知道还有其他可用的 http 网络库),它使用 ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
检查(在执行 http 之前)请求)如果用户连接到互联网(一种快速失败策略)。
我的问题是我应该将 ConnectivityManager
保存为我的 http 库的实例变量(类字段)还是应该调用 ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE );
每次在我开始一个 http 请求之前检索一个“新的”ConnectivityManager?每次我调用 getSystemService(Context.CONNECTIVITY_SERVICE)
时是否返回相同的 ConnectivityManager 实例(换句话说,将 ConnectivityManger 存储到类字段中会导致问题,因为我的 http 库是长期存在的 -> 只要应用程序运行就存在)
最佳答案
My question is should I save the ConnectivityManager as an instance variable (class field) of my http library or should I call ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); every time before I start an http request to retrieve a "new" ConnectivityManager?
我会保留实例。虽然 getSystemService()
实际上调用起来并不昂贵,但为什么调用它的次数比需要的多?
in other words, can storing a ConnectivityManger into a class field lead to problems since my http library is a long living one --> lives as long as application run
为了安全起见,请在Application
单例(getApplicationContext()
) 上调用getSystemService()
。 通常,getSystemService()
返回的对象对创建它的Context
一无所知。偶尔,它确实存在——Android 5.0 中的 CameraManager
遭受此缺陷,尽管它已在 Android 5.1 中得到修复。如果系统服务对象的生命周期将超过我所在的上下文,我倾向于使用 getApplicationContext()
来检索系统服务,以免偏执。
(内存泄漏,他们是来找我的!)
Is the same ConnectivityManager instance returned every time I call getSystemService(Context.CONNECTIVITY_SERVICE)
老实说,我从来没有看过。
关于android - context.getSystemService() 是一个昂贵的电话吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32417398/