César Puerta

César Puerta

Software Engineer @ Twitter. Living in San Francisco and enjoying it more and more every day

Highlighted by César Puerta

See more

Service is how an application indicates to the operating system that it needs to perform a longer-running operation outside of the normal Activity UI flow. It may be self-running (through Context.startService()), or running on behalf of of another process (through Context.bindService()). If you do not need either of these behaviors, you should not use a Service. For example, if you have background work to do that does not need to keep itself running (such as downloading content for your UI that you could resume later when the user returns to the UI) you should use local threading primitives such as AsyncTask, Loader, HandlerThread, etc. Using a Service is much more resource-intensive (as your service needs to be tracked as part of the global system state) and opens the door to all kinds of bad bugs where your services is left running when it shouldn’t be (this is a very common problem in Android apps, and is harmful to the system). Likewise, if you want to have an association between two pieces of code but they are running in the same local process, don’t use bindService(); instead, use regular callbacks and other facilities. This will be easier to write, easier to understand, and less resource-intensive. Also, beware a common gotcha with AsyncTask: given the asynchronous nature of AsyncTask, it’s possible that an Activity may finish by the time that results come back in. Make sure that you check the status of the Activity before using those results.