Accessing a database in a separate thread in Android
-
28-09-2019 - |
문제
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?
해결책
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.