在 Android 中的单独线程中访问数据库
如何在 Activity
的单独线程(即 AsyncTask
)中访问 SQLiteDatabase
数据库,并确保始终将其保留在一个合法的国家?
如果我理解正确,线程可以随时被终止,并且数据库可能保持打开状态,可能会给出 IllegalStateException
(SQLiteDatabase 创建且从未关闭)在稍后的时间。
你如何处理这个问题?
How do you access a SQLiteDatabase
database in a separate thread (ie: an AsyncTask
) of an Activity
and make sure that you always leave it in a legal state?
If I understand correctly, the thread can be killed at any moment and the database might remain open, potentially giving an IllegalStateException
(SQLiteDatabase
created and never closed) at a latter time.
How do you deal with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的
AsyncTask
由您的Activity
管理,那么Activity
可能会在适当的时候(当它变得容易受到攻击时)取消AsyncTask
被操作系统杀死,例如在Activity.onPause()
之后),因此AsyncTask.onCancelled()
将在您可以关闭数据库的地方被调用。如果您的
AsyncTask
(或Thread
)不是由您的Activity
管理,那么您就会遇到麻烦,应该考虑重新设计您的架构。If your
AsyncTask
is managed by yourActivity
, thenActivity
may cancelAsyncTask
in proper time (when it becomes vulnerable to be killed by OS, e.g. afterActivity.onPause()
) soAsyncTask.onCancelled()
will be called where you may close the DB.If your
AsyncTask
(or aThread
) is not managed by yourActivity
then your are in trouble and should consider redesigning your architecture.有两种方法:
您可以注册一个
Runtime.addShutdownHook(..)
并在那里关闭数据库。创建自定义
应用程序
并在关闭数据库时实现onLowMemory()
。Two ways:
You can register a
Runtime.addShutdownHook(..)
and close database there.Create custom
Application
and implementonLowMemory()
where you close the database.