Accessing a database in a separate thread in Android
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 mig开发者_如何转开发ht remain open, potentially giving an IllegalStateException
(SQLiteDatabase
created and never closed) at a latter time.
How do you deal with this?
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.
Two ways:
You can register a
Runtime.addShutdownHook(..)
and close database there.Create custom
Application
and implementonLowMemory()
where you close the database.
精彩评论