应该在服务或 AsyncTask 中使用 SQLiteOpenHelper (Android) 吗?

Should an SQLiteOpenHelper (Android) be used in a service or an AsyncTask?

我进行了搜索,但没有找到此问题的任何具体答案;就这样吧。

我知道我不应该从 UI 线程访问数据库。此外,AsyncTask 不适用于较长时间的任务(内存泄漏等)。所以我猜我应该使用服务。

我应该在新线程中将 SqliteOpenHelper 作为服务打开吗?您有如何执行此操作的示例代码吗?

SQLiteOpenHelper 是否由 Android 在另一个线程中自动 运行?我没有在 UI 线程上找到任何没有 运行 SQLiteOpenHelper 的在线示例代码。这是为什么?

谢谢!

Is the SQLiteOpenHelper automatically run in another thread by Android?

在 Java 中,对象不在线程上 运行。在线程上调用方法。

我不知道有任何 SQLiteOpenHelper 方法会自动使用自己的线程 — 线程管理是调用 SQLiteOpenHelper 方法的对象的责任。

I didn't find any example code online that didn't run the SQLiteOpenHelper on the UI thread

在 Java 中,对象不在线程上 运行。在线程上调用方法。

Here is a sample app that calls methods like getReadableDatabase() on a SQLiteOpenHelper from a background thread. Here is another such sample app. Here is yet another sample app。前两个使用AsyncTask;后者使用带有事件总线的常规 Thread

Should I open the SqliteOpenHelper as a service in a new Thread?

一个SQLiteOpenHelper不能一个Service,因为Java不支持多重继承,SQLiteOpenHelperService具体类.

当然欢迎您在 Service 中使用 SQLiteOpenHelper 的实例,如果您愿意的话。

Also, the AsyncTask isn't good for longer time tasks(memory leaks etc.).

正确使用 AsyncTask 不会触发内存泄漏(例如,通过保留的片段管理它)。是否使用 AsyncTask 还是其他东西(例如,普通线程,IntentService)的决定更多地取决于工作将花费多长时间以及您的进程在此之前终止的风险是什么工作完成。