开发者

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:

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜