微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – context.getSystemService()是一个昂贵的调用?

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 singleton(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)

说实话,我从来没有看过.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐