最好的办法,从服务交付导致Android的结合 [英] The best way to deliver result from Service binding in Android
问题描述
如何从服务结果,如果任务异步运行?
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
}
}
当然,它是通过ServiceConnection工作。在平时上课,我会用接口回调,但如果我同样在这里做,活动实例将通过回调服务泄露。
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?
推荐答案
我会用的 LocalBroadcastManager 播出的意图
包含结果,让任何有兴趣的活动,可以注册并在服务完成其任务接收广播。
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.
如果该数据是复杂的,是不实际的打包成一个意图
,你需要得到一点创意。你应该使用的ContentProvider
,并把内容URI到意向该活动就可以用它来查询结果。或者您可能能够将结果存储在一个静态单(或在您的应用程序实例),只是有活动时,它接收广播检索更新后的值。这取决于你的需求。
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.
希望帮助!
这篇关于最好的办法,从服务交付导致Android的结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!