Search code examples
androidmultithreadingsqlitealarmmanager

Using sqlite in thread that runs from alarmmanager


I want to create a simple Service (based on the ApiDemos\app\AlarmService_Service example) In the service's thread I want to add a record to a local DB every 15Sec.

But the problem is that the DataSource I created (with the help of http://www.vogella.com/articles/AndroidSQLite/article.html article) needs Context object in order to initiate the DataSource.

In the near future I'll want a service like this example to run also when the device booted. So my qustion is how can I use sqlite in situation where I have no Context?


Solution

  • So my qustion is how can I use sqlite in situation where I have no Context?

    Service inherits from Context, and so you have a Context. Bear in mind that you need to have a singleton SQLiteOpenHelper (or SQLiteDatabase) if you expect other threads to also be using the database.

    BTW, that sample is quite possibly the worst Google has ever published. I am not completely clear on why the user wants you to "add a record to a local DB every 15Sec" in the background, but that sample:

    • will fail to keep the device awake
    • displays a Notification for no particular reason
    • has you roll your own thread rather than using IntentService which handles that for you
    • does not handle multiple commands sent to the service
    • has a largely pointless Binder
    • etc.

    The proper way to use AlarmManager with _WAKEUP alarms is either to use my WakefulIntentService or the Android Support package's WakefulBroadcastReceiver. I have published a sample using WakefulIntentService with AlarmManager and an equivalent sample using WakefulBroadcastReceiver.