启动服务并返回数据
今天我正在学习意图并将活动绑定到服务,我发现将数据从服务传输到活动非常简单且很好的方法。我想测试一个将启动服务的活动,该服务将调用网页来获取一些数据。我将活动绑定到服务,以便活动可以调用服务方法,然后烘烤结果。在服务方法中,我调用网页并返回数据。当我测试它时,我收到了一个空指针异常,我很确定我没有以正确的方式执行此操作,是否有人对如何正确实现它有任何建议。
today I was learning about Intents and binding an activity to service, I found it quite easy and great way to transfer data from the service to the activity. I wanted to test out an activity that would start a service, this service would call on a webpage to get some data. I binded the activity to the service so that the activity could call on the service method and then toast the results. In the service method I call on a webpage and return the data. When I tested it I was getting a null pointer exception, im pretty sure I am not doing it the right way , does anyone have any suggestions how to implement this properly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在这里处理一些相当可靠的线程同步问题。注册某种侦听器范例会更好,这样您就可以将 Activity 注册为服务正在生成的数据的侦听器。就目前而言,您的服务和活动之间根本不存在同步,导致活动在准备好之前尝试从服务中获取结果。有大量资源讨论侦听器模式或观察者模式。
我应该指出,我不知道你的服务是否真的正确地把事情拉下来。我只是看你们两人之间的沟通。
You're dealing with some fairly solid thread synchronization issues here. You would be far better served registering some kind of listener paradigm such that you register your Activity as a listener to the data that your Service is producing. As it currently stands, there's no synchronization between your Service and Activity at all, resulting in the Activity trying to fetch the results from the Service before they're ready. There are a ton of resources out there discussing the listener pattern or Observer pattern.
I should note, I have no idea whether your Service is actually pulling things down correctly. I'm just looking at your communication between the two.
当从 service 返回结果时,最好在 Activity 中实现 ResultReceiver 接口,并通过 putExtra 将接收者对象传递给服务。在您的服务中获取接收者对象并调用 receiver.send() 函数来发送 Bundle 中的任何内容。 [我至少在 IntentService 中测试了这种模式]。
编辑:查看这篇文章以了解完整的实现。
When returning results from service , its better to implement ResultReceiver interface in you activity and pass receiver object to the service via putExtra. In your service fetch the receiver object and call receiver.send() function to send anything in Bundle. [I have tested this pattern in IntentService at least].
Edit:check out this post for complete implementation.