If we need some background activities to go on only while application/
Activity
is active, a thread can do the required work.
If we need a component that keeps active even when, after a while, the Android system decides to remove your
Activities
from memory, or application doesn't require user interaction for long, so there is no "Activities" with which user interacts then - Service should be the obvious choice, or even a "foreground service", which is considered even more important by the Android system and even less likely to be terminated to reclaim resources.
A service is, of course, the way to go if you want to provide some service(s) to other applications, which can "bind" to a service only.
In Android, a
Service
does not provide any concurrent execution ("run in background"). It is actually more of a simple Java object which merely is instantiated (and managed) via the Android system instead of your application via new
.
The most important property of a service is therefore not about deferring workload; this can be achieved with simple threads.
Service is part of Android system and it has the provision to also runs in the separate process and bind to the other application running in different processes.
Service always runs in the main thread of the application while thread runs on its own thread.
if you use an
AsyncTask
for a long-running process it may continue after you've navigated away from the Activity
but:- If the
Activity
is in the background when your processing is complete you may have problems when you try to update the UI with the results etc. - A background
Activity
is far more likely to be killed by Android when it needs memory than aService
.
All components of the same application usually run in the same process. When new component is started, it will , by default, run in the same thread and inside the application main process unless you provide some thing else. For example if you run a service by startService() method from an activity, this service runs in the main application process and thread. This is called “Single Thread Model”.
No comments:
Post a Comment