tags:

views:

81

answers:

1

I have scoured the web, I can't seem to figure out how to make an Android service actually DO anything. I have found lots of examples of how to create a basic one, but none of the examples seem to show how to call the service from an activity, and have the service do something.

For example, I would like to have a service running that will send a TCP text message to a server when requested. I can make the service, and have it run, but how the heck do I have the Activity make the call that passes a string to the method in the service that will send the TCP message?

This seems like it should be somewhat easy, but I just can't figure out, or find an example, of how to do it. Maybe I am not understanding what a service should be used for? I definitely want it running for a long period of time, no gui needed, and "service" requests to send TCP messages....hum...

+1  A: 

I can make the service, and have it run, but how the heck do I have the Activity make the call that passes a string to the method in the service that will send the TCP message?

Use the local binding pattern. In this sample project, an activity binds to a service, in order to get some data retrieved by that service (weather forecast) based on a location change. In this sample project, an activity binds to a service to register a listener object to be notified of changes in a user's identi.ca timeline.

Or, use an IntentService and startService() to send a command to be processed by the IntentService. In this sample project, I implement an IntentService that executes a BeanShell script supplied by a caller. In this sample project, I implement an activity that sends the BeanShell script to the IntentService. This pair of examples is designed to demonstrate using this technique across applications, but the approach works fine within a single application as well.

I definitely want it running for a long period of time

No you don't.

CommonsWare
If you are just learning I would stick with the intent API and leave the binding pattern alone, it is a lot more difficult to understand, and leaves you constantly checking if your reference to your service is null. IntentService is a good place to start http://developer.android.com/reference/android/app/IntentService.html
schwiz