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...
You can do this by making your own Interface where you declare for example " isServiceRunning() ". You can then bind your Activity to your Service, run the method isServiceRunning(), the Service will check for itself if it is running or not and returns a boolean to your Activity.
Stopping a service. You stop a service via the stopService() method. No matter how frequently you called the startService(intent) method, one call to the stopService() method stops the service. A service can terminate itself by calling the stopSelf() method.
Caution: A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise. You should run any blocking operations on a separate thread within the service to avoid Application Not Responding (ANR) errors.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With