1

I have a service which does some work, when done, it send a broadcast. In activity the receiver is registered and pick up the broadcast in its onReceive. Now I need to select data from database and show them inside listview. But I dont want to do the database select on ui thread because that can be expensive operation, I want to open async task, but thats agains the lifecycle of receiver. What other solution do I have ? To open service ? Yes I can do the database operation in new service but how can I then deliver the data to the views from service ? Updating views from service is for sure something I dont want to do. I am in a kind of deathlock right now.

Thanks for any ideas

edit 1: this is the explanation from android documentation why you cannot use AsyncTask in onReceive and why the answers are invalid

Receiver Lifecycle A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active. This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes. In particular, you may not show a dialog or bind to a service from within a BroadcastReceiver. For the former, you should instead use the NotificationManager API. For the latter, you can use Context.startService() to send a command to the service.

edit 2: The answers led me to a solution, to create a handler in the activity and pass it to the receiver, in its onReceive just post message to the handler and then inside the handler open the async task and do the database stuff. Not sure though if this is a good one.

4

1 回答 1

0

我的建议是创建一个Interface将数据返回到Activity您可以填充ListView. 我刚刚创建了一个演示AsyncTask,我在其中执行数据库操作AsyncTask并将数据发送到Activity使用Interface并更新 UI。因此,您可以尝试替换AsyncTaskService执行您自己的操作。Here is a sample demo source for Database Operation in AsyncTask and returning its content to Activity.

于 2012-09-03T08:46:12.190 回答