在Android中保留成员对系统服务的引用是否有益?
假设我有一个使用系统服务(例如PowerManager,WifiManager等)的android Activity/Service……让私有成员在构造函数或onCreate方法中保持对这些服务的引用一次而不是获取那些是有益的服务经理每次都需要通过调用getSystemService(...)`吗?如果是这样,这些系统服务之一崩溃并重新启动时,这些成员是否可以安全使用?如果它们不安全,那么处理此类服务死亡案例的正确方法是什么?
Suppose I have an android Activity / Service that is using system services such as PowerManager, WifiManager, etc... Is it beneficial to have private members for keeping reference to those services once in the constructor or onCreate method instead of getting those service managers each and every time they are needed by calling getSystemService(...)`? If so, are those members safe to use in case one of those system services crash and restart? If they aren't safe, what is the right approach for handling such cases of service death?
让私有成员在构造函数或onCreate方法中保留一次对这些服务的引用,而不是每次通过调用getSystemService(...)来获取每次需要的那些服务管理器,都是有益的?
s it beneficial to have private members for keeping reference to those services once in the constructor or onCreate method instead of getting those service managers each and every time they are needed by calling getSystemService(...)`?
当然!这样的打字方式更少了. :-)
Sure! It's less typing that way. :-)
如果是这样,这些系统服务之一崩溃并重新启动时,这些成员是否可以安全使用?
If so, are those members safe to use in case one of those system services crash and restart?
如果系统服务崩溃,则与应用程序相比,用户所遇到的问题要大得多.话虽如此,您可能会得到某种RuntimeException
.
If a system service crashes, the user has bigger problems than what happens with your app. That being said, you might get some sort of RuntimeException
.