Reputation: 23354
I am using BroadcastReceiver
that gets the stream of data at regular intervals and then based on that data I am doing certain database operations to insert that data into various tables.
The problem is that although you can do database operations inside BroadcastReceiver
but the receiver can return at any time. Morever, I like to do such database operations in an AsyncTask
.
But because it is still not a good practice to start AsyncTask
from BroadcastReceiver
for the same reason that Android may kill your process if onReceive()
returned and there is no other active components running, so I am left with a Service
(AFAIK) to do database related work. And this Service should manage AsyncTask
. This way Android will be aware about the active component and Android will not kill the process.
That is-
BroadcastReceiver ==> Service ==> AsyncTask ==> SQLITE (INSERT)
And if so, then how about IntentService
instead of Service
?
I have a singleton Adaptor from SQLiteOpenHelper
class, so I can use the context
that I will receive from onReceive()
of BroadcastReceiver
to use the adapter for database operations.
But the approach seems inefficient.
Please suggest..
Upvotes: 1
Views: 1158
Reputation: 1007339
Is this the best approach to do so for the given scenario ?
I would use an IntentService
rather than a Service
with an AsyncTask
. An AsyncTask
is only used when you have work that needs to be done on the main application thread, and a service should not have work that needs to be done on the main application thread.
Beyond that, though, having a manifest-registered BroadcastReceiver
delegate the work to a Service
is a typical approach.
What if I do database operations in BroadcastReceiver itself ?
If your UI happens to be in the foreground, it will be frozen while onReceive()
is executing.
If you take several seconds to do the work, you will get the background equivalent of an ANR and your work will be interrupted without completion.
Hence, I suggest using the IntentService
.
Upvotes: 1
Reputation: 393
Why don't you try ExecutorService instead of AsyncTask? Have a look at : http://developer.android.com/reference/java/util/concurrent/ExecutorService.html http://developer.android.com/reference/java/util/concurrent/Executor.html
Upvotes: 0