starting a service and returning data

2019-08-10 06:02发布

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.

2条回答
叼着烟拽天下
2楼-- · 2019-08-10 06:22

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.

查看更多
疯言疯语
3楼-- · 2019-08-10 06:32

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.

查看更多
登录 后发表回答