android - context.getSystemService() 是一个昂贵的电话吗?

标签 android android-context

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/

相关文章:

java - 我应该在这里为 Android 上下文使用什么?

android - 如何防止未经授权的客户端访问我的服务器

java - 当编辑文本为空/非空时如何禁用/启用按钮

java - Android单元测试: Mock context that also returns a looper

android - 新 Activity 空指针异常

java - getApplicationContext() 返回 null,但在其他 Activity 中有效

android - 使用 onShake 方法启动新 Activity

android - 房间关系插入删除更新和排序

android - Flurry 在 android 中什么都不做

java - 当从另一个 Activity 调用时,Android 中的 Sharedpreferences 返回 null