关闭数据库中的ContentProvider数据库中、ContentProvider

2023-09-12 00:43:17 作者:再撸剁手#

这一周,我一直在学习所有关于ContentProvider的,并使用SQLiteOpenHelper类来管理供应商的内部数据库的创建和升级。具体而言,我一直在读通过从SDK的样本目录中的记事本的例子。

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讨论正朝着正确的方向)。如果我是在一个活动使用类的话,我会简单地调用close()中的onDestroy()方法,但据我所知,ContentProvider的不具有相同的生命周期中的活动做。在code,记事本似乎永远不会调用close(),所以我想假设它是由SQLiteOpenHelper或其他一块拼图处理,但我真的很想知道。我真的不相信样品code多,要么...

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?

推荐答案

据到戴安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.

 
精彩推荐