问题
How to get result from the Service, if task run asynchronously?
If a task is started synchronously in main thread, there is no problem:
Object result = serviceInstanceInActivity.callMethod();
But if the task runs in other thread, we have a problem:
void asyncMethodInService() {
new MyTask().execute();
}
class MyTask extends AsyncTask<Void, Void, Result> {
// implementation of the others methods
public void onPostExecute(Result result) {
// We need to send data to Activity here
}
}
Of Course, it's work via ServiceConnection. In usual class, I would use interfaces as callback, but if I do same here, the Activity instance will leaked in Service via callback.
So, what is recommended way to deliver data in this cases?
回答1:
I would use LocalBroadcastManager to broadcast an Intent containing the result, so that any interested activities can register for and receive the broadcast when the service completes its task.
If the data is complex and is not practical to pack into an Intent, you need to get a bit creative. You should probably use a ContentProvider and put a content URI into the intent which the activities can then use to query for the result. Or you might be able to store the result on a static singleton (or on your application instance) and just have the activity retrieve the updated value when it receives the broadcast. It depends on your requirements.
Hope that helps!
来源:https://stackoverflow.com/questions/17460013/the-best-way-to-deliver-result-from-service-binding-in-android