Reputation: 101
An activity can use AsyncTask or Handler framework for background work. Both will continue to work even after user has moved away from the activity that started them and the onDestroy for the activity has been called. In other words, an activity is fully capable of doing background work even after its GUI has been shutdown.
In this scenario, use of Service for background work seems like redundancy. What does Service bring to the table that an activity can not do? Thanks.
Upvotes: 10
Views: 3128
Reputation: 1586
@BraynDenny answer is good enough, I would like to explain in another perspective.
Firstly you misunderstood the meaning of background tasks, definition of service says Service continuously runs in background even if the app is not in foreground, here the term background does not mean separate thread, it means the service runs when you close the application unlike Activity, also service runs in main thread by default, if you want a asynchronous service use intentService
an activity is fully capable of doing background work even after its GUI has been shutdown.
What you said about is absolutely wrong. Activity, Service are components of Android, but AsyncTasks or Threads are not components when you kill an activity the Asynctask in the activity also gets killed since the Asynctask instance is created inside activity class, but when you start downloading a file using foreground Service it is not killed even when you close the application, just like the music applications in Android, even if you close the app the music still plays in the background, showing a foreground notification
There are three different kind of services, to know more about them please check this link https://developer.android.com/guide/components/services.html#CreatingBoundService
Upvotes: 0
Reputation: 28541
AsyncTask allows you to easily perform UI updates while also to clearly separate UI thread and working thread logics. However, other applications will not be able to access your AsyncTask. In that case you need the services.
Upvotes: 0
Reputation: 9595
When the UI shown by Activity goes to background(by pressing home button), it is not guaranteed that Activity exists for long time, framework might decide it to stop it.
Upvotes: 0
Reputation: 27596
What is a Service?
Most confusion about the Service class actually revolves around what it is not:
Thus a Service itself is actually very simple, providing two main features:
Read the rest of the documentation for more info
So one instance of a service would be something you want to happen at set intervals on its own without having to launch an activity or anything else to "launch" it. For example, SMSBackup is just a service that runs in the background, polling every X minutes your SMS messages and copies them into a gmail label, as a "backup" service.
Upvotes: 8