在 ContentProvider 中关闭数据库 [英] Closing the database in a ContentProvider

查看:35
本文介绍了在 ContentProvider 中关闭数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本周我一直在学习关于 ContentProvider 的所有内容,并使用 SQLiteOpenHelper 类来管理提供者内部数据库的创建和升级.具体来说,我一直在阅读 sdk 示例目录中的 NotePad 示例.

This week I've been learning all about ContentProvider and using the SQLiteOpenHelper class to manage the creation and upgrading of the database inside of a provider. Specifically, I've been reading through the NotePad example from the sdk's samples directory.

现在,我可以看到 SQLiteOpenHelper 有一个 close() 方法.我知道让空闲数据库打开是不好的做法,可能会导致内存泄漏等(除非 this 讨论朝着正确的方向前进).如果我在 Activity 中使用该类,那么我只需在 onDestroy() 方法中调用 close(),但据我所知,ContentProvider 没有与 Activity 相同的生命周期.NotePad 的代码似乎从未调用 close(),所以我想假设它是由 SQLiteOpenHelper 或其他一些难题处理的,但我真的很想知道.我也不太相信示例代码...

Now, I can see that SQLiteOpenHelper has a close() method. I'm aware that leaving idle databases open is bad practice and can cause memory leaks and whatnot (unless this discussion is headed in the right direction). If I were using the class in an Activity, then I would simply call close() in the onDestroy() method, but as far as I know, ContentProvider does not have the same life cycle that activities do. The code for NotePad never seems to call close(), so I would like to assume that it is handled by SQLiteOpenHelper or some other piece of the puzzle, but I'd really like to know for sure. I don't really trust the sample code that much, either...

问题摘要:我们应该什么时候关闭提供程序中的数据库?

Question summary: When should we close the database in a provider, if at all?

推荐答案

根据Dianne Hackborn(Android 框架工程师)无需关闭内容提供程序中的数据库.

According to Dianne Hackborn (Android framework engineer) there is no need to close the database in a content provider.

内容提供者在其托管进程创建时创建,并且只要进程存在,就会一直存在,所以没有必要关闭数据库——它将作为内核的一部分关闭当进程被杀死时清理进程的资源.

A content provider is created when its hosting process is created, and remains around for as long as the process does, so there is no need to close the database -- it will get closed as part of the kernel cleaning up the process's resources when the process is killed.

感谢@bigstones 指出这一点.

Thanks @bigstones for pointing this out.

这篇关于在 ContentProvider 中关闭数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆