在 Android 中的单独线程中访问数据库

发布于 2024-10-05 00:17:46 字数 260 浏览 0 评论 0原文

如何在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

栖竹 2024-10-12 00:17:46

如果您的 AsyncTask 由您的 Activity 管理,那么 Activity 可能会在适当的时候(当它变得容易受到攻击时)取消 AsyncTask被操作系统杀死,例如在Activity.onPause()之后),因此AsyncTask.onCancelled()将在您可以关闭数据库的地方被调用。

如果您的 AsyncTask (或 Thread)不是由您的 Activity 管理,那么您就会遇到麻烦,应该考虑重新设计您的架构。

If your AsyncTask is managed by your Activity, then Activity may cancel AsyncTask in proper time (when it becomes vulnerable to be killed by OS, e.g. after Activity.onPause()) so AsyncTask.onCancelled() will be called where you may close the DB.

If your AsyncTask (or a Thread) is not managed by your Activity then your are in trouble and should consider redesigning your architecture.

倦话 2024-10-12 00:17:46

有两种方法:

  1. 您可以注册一个Runtime.addShutdownHook(..)并在那里关闭数据库。

  2. 创建自定义应用程序并在关闭数据库时实现onLowMemory()

Two ways:

  1. You can register a Runtime.addShutdownHook(..) and close database there.

  2. Create custom Application and implement onLowMemory() where you close the database.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文