调用从活动中一个漫长的服务方法 - 最佳实践 [英] Calling a lengthy Service method from an Activity - Best Practice

查看:75
本文介绍了调用从活动中一个漫长的服务方法 - 最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发与转接给一个Web服务的服务,而把这些调用的一些活动的应用程序。这些活动需要处理这些调用的结果。例如,我对服务,访问Web服务并返回关于新批示某些信息的writeComment方法。

I'm developing an app with a service that forwards calls to a web-service, and a few activities that place those calls. The activities need to process the results of those calls. For example, I have a writeComment method on the service, that accesses the web-service and returns some information about the newly written comment.

现在我让活动采取所有线程的照顾。活动绑定服务,然后使用该调用绑定服务的writeComment方法的AsyncTask的。

Right now I let the Activity take care of all the threading. The Activity binds the service, and then uses an AsyncTask that calls the bound service's writeComment method.

一切运作良好,只要而AsyncTask的运行活动不会停止。如果是这样(轻松地翻转手机时发生),则AsyncTask的死亡试图更新onPostExecute的UI时一个暴力死亡。我不完全知道如何解决这个问题 - 我的的需要让用户知道服务器已经更新

All works well as long as the Activity isn't stopped while the AsyncTask is running. If it does (easily happens when flipping the phone), the AsyncTask dies a violent death when trying to update the UI in onPostExecute. I'm not entirely sure how to fix this - I do need to let the user know the server has been updated.

如果我去了其他方式,并注册服务回调,我还是有点树桩,因为我需要通知服务活动已经改变了 - 我需要告诉它不要通知我的第一个活动的onDestory,并重新注册在第二个活动的onCreate。我需要处理情况的onDestroy后的onCreate之前异步任务完成的情况。

If I go the other way around, and register a callback with the Service, I'm still a bit stump, because I need to notify the Service the Activity has changed - I need to tell it not to notify me in the first Activity's onDestory, and reregister in the second Activity's onCreate. And I need to handle the case where the asynchronous task completes after onDestroy and before onCreate.

什么是最好的做法在这种情况下?

What is considered Best Practice in this case?

谢谢,
  伊泰。

Thanks, Itay.

推荐答案

在我的应用程序,我有一个长期运行的服务,并需要在服务来呈现数据的活动。该服务还执行ping活动时有变化,但活动还可以查询服务。我走近这个问题的方法是双重的。

In my app, I have a long-running service and Activities that need to render data in the service. The service also pings the Activities when there is a change but the Activity can also query the service. The way I approached this was two-fold.

首先,我结合我的活动到服务,以便从活动消息发送到服务。

Firstly, I bind my activity to the Service in order to send messages from Activity to service.

其次,服务发送通知与广播和活动监听这些广播。我设置了在活动onResume和撕裂下来的的onPause。我觉得这是你缺少的部分。

Secondly, the Service sends notifications with Broadcasts and the Activity listens for those broadcasts. I set that up in the Activity onResume and tear it down in the onPause. I think this is the part that you're missing.

这篇关于调用从活动中一个漫长的服务方法 - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆