是否有一些标准方法可以显式关闭服务和其他资源?
例如,当使用数据库连接、线程或 IO 流(所有需要显式关闭/释放的内容)时,是否有一些标准方法可以做到这一点?也许通过实现一些标准接口,框架/类消费者将能够为我的类调用此资源清理逻辑?
对于那些对.NET Framework
有一定经验的人来说,类似的就是IDisposable
接口,因此通过实现这个接口,我可以将所有资源清理逻辑放在Dispose()中
方法,以便类使用者能够检查类的实例是否实现了 IDisposable
接口,然后显式调用 Dispose()
。
Android 也有内置的东西吗?
For instance when using database connection, threading or IO streams (all what is required explicit closing/free up) is there some standard way of doing this? Perhaps by implementing some standard interface so Framework/class consumer would be able call this resources cleanup logic for my class?
For those who have some experiance with .NET Framework
analogue would be IDisposable
interface, so by implementing this interface I can put all resource-cleanup logic in Dispose()
method so class consumers would be able check whether an instance of a class implements IDisposable
interface and then call Dispose()
explicitly.
Is there something built in Android as well?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,服务和活动都有生命周期。当它们“关闭”时,将调用 onDestroy() 方法。 Android 中有多种生命周期方法,了解何时使用什么方法非常重要。以下页面对此进行了描述:
http://developer.android.com/reference/android/app/Activity.html
http://developer.android.com/reference/android/app/Service.html
从这些 onDestroy() 方法中,您应该关闭您的资源。
如果您有很多资源需要关闭,您可能希望让它们实现一个接口并将这些资源存储到一个集合中,以便您可以在调用 onDestroy 时循环访问您的资源。
Yes, Services and Activities have lifecycles. When they are 'closed', the onDestroy() method will be called. There are multiple lifecycle methods in Android and it is really important to learn when to use what. This is described on the following pages:
http://developer.android.com/reference/android/app/Activity.html
http://developer.android.com/reference/android/app/Service.html
From these onDestroy() methods, you should close your resources.
If you have a lot of resources to close, you might want to let them implement an interface and store these resources into a collection so that you can loop through your resources when onDestroy is called.