서비스 대 IntentService
누군가가 나에게 함께 할 수있는 뭔가의 예를 보여 주시겠습니까 IntentService
수행 할 수 없습니다 Service
(반대 등)?
나는 또한 IntentService
다른 스레드에서 실행되고 a 는 실행 Service
하지 않는다고 믿습니다 . 따라서 내가 볼 수있는 한 자체 스레드 내에서 서비스를 시작하는 것은 IntentService
. 그렇지 않습니까?
누군가가 내 두 가지 질문에 모두 나를 도울 수 있다면 감사하겠습니다.
Tejas Lagvankar는 이 주제에 대한 멋진 게시물을 작성했습니다 . 다음은 Service와 IntentService의 몇 가지 주요 차이점입니다.
언제 사용합니까?
서비스는 어떤 UI와 작업에 사용할 수 있지만, 너무 오래해서는 안됩니다. 긴 작업을 수행해야하는 경우 서비스 내에서 스레드를 사용해야합니다.
IntentService은 일반적으로 주 스레드없이 통신 긴 작업에 사용할 수 있습니다. 통신이 필요한 경우 메인 스레드 핸들러 또는 브로드 캐스트 인 텐트를 사용할 수 있습니다. 또 다른 사용 사례는 콜백이 필요한 경우입니다 (인 텐트 트리거 작업).
트리거하는 방법?
서비스는 메서드를 호출하여 실행됩니다
startService()
.IntentService는 이 새 작업자 스레드를 생성합니다 및 방법은, 인 텐트를 사용하여 트리거 방식입니다
onHandleIntent()
이 스레드에서 호출됩니다.
에서 트리거
- 서비스 와 IntentService는 어떤 스레드, 활동 또는 다른 응용 프로그램 구성 요소에서 트리거 될 수 있습니다.
실행
서비스는 백그라운드에서 실행하지만 응용 프로그램의 메인 스레드에서 실행됩니다.
IntentService은 별도의 작업자 스레드에서 실행됩니다.
한계 / 단점
서비스는 응용 프로그램의 주 스레드를 차단할 수 있습니다.
IntentService는 병렬로 작업을 실행할 수 없습니다. 따라서 모든 연속 인 텐트는 작업자 스레드의 메시지 대기열로 이동하여 순차적으로 실행됩니다.
언제 멈출까요?
당신이 구현하는 경우 서비스를 , 그것의 작업이 호출하여 수행하는 경우 서비스를 중지하는 것은 귀하의 책임입니다
stopSelf()
또는stopService()
. (바인딩 만 제공하려는 경우이 메서드를 구현할 필요가 없습니다).IntentService은 당신이 전화를하지 않아도되도록 모든 시작 요청이 처리 된 후 서비스를 중지합니다
stopSelf()
.
누군가가 a로 할 수있는 일의 예를 보여줄 수 있고
IntentService
a로 할 수없는Service
일과 그 반대의 경우.
정의상 불가능합니다. Java로 작성된 IntentService
의 하위 클래스입니다 Service
. 따라서, 아무것도이 IntentService
수행하는이 Service
코드의 해당 비트가 포함시킴으로써, 할 수있는 IntentService
용도.
자체 스레드로 서비스를 시작하는 것은 IntentService를 시작하는 것과 같습니다. 그렇지 않습니까?
의 세 가지 주요 기능은 다음 IntentService
과 같습니다.
백그라운드 스레드
에
Intent
전달 된 s 의 자동 대기열onStartCommand()
, 따라서 하나Intent
가onHandleIntent()
백그라운드 스레드에서 처리되는 경우 다른 명령이 차례를 기다리는 대기열에 추가됩니다.대기열이 비어있는 경우에
IntentService
대한 호출을 통해 의 자동 종료stopSelf()
이 모든 것은 Service
확장하지 않고 IntentService
.
서비스
- 호출자
startService()
- 모든 항목에서 트리거
Thread
- 실행
Main Thread
- 메인 (UI) 스레드를 차단할 수 있습니다. 긴 작업을 위해 항상 서비스 내에서 스레드 사용
- 작업이 완료되면 전화로 서비스를 중지
stopSelf()
하거나stopService()
IntentService
- 통신이 다음 필요가 수행되는 경우는 보통 긴 작업을 메인 스레드와의 통신을 수행하지 않습니다
Handler
또는BroadcastReceiver
- 다음을 통해 호출
Intent
- 에서 트리거
Main Thread
- 별도의 스레드에서 실행
- 작업을 병렬로 실행할 수 없으며 여러 인 텐트가 동일한 작업자 스레드에 대기 중입니다.
수락 된 답변에 점수 추가 :
Android API 내에서 IntentService 사용을 참조하십시오. 예 :
public class SimpleWakefulService extends IntentService {
public SimpleWakefulService() {
super("SimpleWakefulService");
}
@Override
protected void onHandleIntent(Intent intent) { ...}
앱에 대한 IntentService 구성 요소를 만들려면 IntentService를 확장하는 클래스를 정의하고 그 안에 onHandleIntent ()를 재정의하는 메서드를 정의합니다.
Also, see the source code of the IntentService, it's constructor and life cycle methods like onStartCommand...
@Override
public int More ...onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
Service together an AsyncTask is one of best approaches for many use cases where the payload is not huge. or just create a class extending IntentSerivce. From Android version 4.0 all network operations should be in background process otherwise the application compile/build fails. separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. For more discussion of this topic, see the blog post
from Android developers guide:
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent, in turn, using a worker thread, and stops itself when it runs out of work.
Design pattern used in IntentService
: This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
The IntentService class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface's responsiveness. Also, an IntentService isn't affected by most user interface lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask.
An IntentService has a few limitations:
It can't interact directly with your user interface. To put its results in the UI, you have to send them to an Activity. Work requests run sequentially. If an operation is running in an IntentService, and you send it another request, the request waits until the first operation is finished. An operation running on an IntentService can't be interrupted. However, in most cases
IntentService is the preferred way to simple background operations
**
Volley Library
There is the library called volley-library for developing android networking applications The source code is available for the public in GitHub.
The android official documentation for Best practices for Background jobs: helps better understand on intent service, thread, handler, service. and also Performing Network Operations
Don't reinvent the wheel
IntentService extends Service class which clearly means that IntentService
is intentionally made for same purpose.
So what is the purpose ?
`IntentService's purpose is to make our job easier to run background tasks without even worrying about
Creation of worker thread
Queuing the processing multiple-request one by one (
Threading
)- Destroying the
Service
So NO, Service
can do any task which an IntentService
would do. If your requirements fall under the above-mentioned criteria, then you don't have to write those logics in Service
class. So don't reinvent the wheel because IntentService
is the invented wheel.
The "Main" difference
The Service runs on the UI thread while an IntentService runs on a separate thread
When do you use IntentService?
When you want to perform multiple background tasks one by one which exist beyond the scope of an Activity then the IntentService
is perfect.
How IntentService
is made from Service
A normal service runs on the UI Thread(Any Android Component type runs on UI thread by default eg Activity
, BroadcastReceiver
, ContentProvider
and Service
). If you have to do some work which may take a while to complete then you have to create a thread. In case of multiple requests, you will have to deal with synchronization
. IntentService
is given some default implementation which does those tasks for you.
According to developer page
IntentService
creates a Worker ThreadIntentService
creates a Work Queue which sends request toonHandleIntent()
method one by one- When there is no work then
IntentService
callsstopSelf()
method - Provides default implementation for
onBind()
method which is null - Default implementation for
onStartCommand()
which sendsIntent
request to WorkQueue and eventually toonHandleIntent()
I'm sure you can find an extensive list of differences by simply googling something such as 'Android IntentService vs Service'
One of the more important differences per example is that IntentService ends itself once it's done.
Some examples (quickly made up) could be;
IntentService: If you want to download a bunch of images at the start of opening your app. It's a one-time process and can clean itself up once everything is downloaded.
Service: A Service which will constantly be used to communicate between your app and back-end with web API calls. Even if it is finished with its current task, you still want it to be around a few minutes later, for more communication.
IntentService
IntentService
runs on its own thread. It will stop itself when it's done. More like fire and forget. Subsequent calls will be queued. Good for queuing calls. You can also spin multiple threads within IntentService
if you need to- You can achieve this using ThreadPoolExecutor
. I say this because many people asked me "why use IntentService
since it doesn't support parallel execution". IntentService
is just a thread. You can do whatever you need inside it- Even spinning multiple threads. The only caveat is that IntentService
finishes as soon as you spin those multiple threads. It doesn't wait for those threads to come back. You need to take care of this. So I recommend using ThreadPoolExecutor
in those scenarios.
- Good for Syncing, uploading etc …
Service
By Default Service
runs on the main thread. You need to spin a worker thread to do your job. You need to stop service
explicitly. I used it for a situation when you need to run stuff in the background even when you move away from your app and come back more for a Headless service
.
- Again you can run multiple threads if you need to.
- Can be used for apps like music players.
You can always communicate back to your activity using BroadcastReceivers
if you need to.
An IntentService is an extension of a Service that is made to ease the execution of a task that needs to be executed in background and in a seperated thread.
IntentService starts, create a thread and runs its task in the thread. once done, it cleans everything. Only one instance of a IntentService can run at the same time, several calls are enqueued.
It is very simple to use and very convenient for a lot of uses, for instance downloading stuff. But it has limitations that can make you want to use instead the more basic (not simple) Service.
For example, a service connected to a xmpp server and bound by activities cannot be simply done using an IntentService. You'll end up ignoring or overriding IntentService stuffs.
If someone can show me an example of something that you can be done with an
IntentService
and can not be done with aservice
and the other way around.
IntentService
can not be used for Long Time Listening, Like for XMPP Listeners, its a single time operator, do the job and wave goodbye.
Also it has just one threadworker, but with a trick, you can use it as unlimited.
The Major Difference between a Service
and an IntentService
is described as follows:
Service :
1.A Service
by default, runs on the application's main thread.(here no default worker thread is available).So the user needs to create a separate thread and do the required work in that thread.
2.Allows Multiple requests at a time.(Multi Threading)
IntentService :
1.Now, coming to IntentService
, here a default worker thread is available to perform any operation. Note that - You need to implement onHandleIntent()
method ,which receives the intent for each start request, where you can do the background work.
2.But it allows only one request at a time.
Android IntentService vs Service
1.Service
- A Service is invoked using startService().
- A Service can be invoked from any thread.
- A Service runs background operations on the Main Thread of the Application by default. Hence it can block your Application’s UI.
- A Service invoked multiple times would create multiple instances.
- A service needs to be stopped using stopSelf() or stopService().
- Android service can run parallel operations.
2. IntentService
- An IntentService is invoked using Intent.
- An IntentService can in invoked from the Main thread only.
- An IntentService creates a separate worker thread to run background operations.
- An IntentService invoked multiple times won’t create multiple instances.
- An IntentService automatically stops after the queue is completed. No need to trigger stopService() or stopSelf().
- In an IntentService, multiple intent calls are automatically Queued and they would be executed sequentially.
- An IntentService cannot run parallel operation like a Service.
Refer from Here
참고URL : https://stackoverflow.com/questions/15524280/service-vs-intentservice
'your programing' 카테고리의 다른 글
여러 커밋을 선택하는 방법 (0) | 2020.09.29 |
---|---|
공용 저장소에서 이전 Git 커밋으로 롤백 (0) | 2020.09.29 |
로컬 지점이 추적하고있는 원격 지점 찾기 (0) | 2020.09.29 |
.net의 app.config 또는 web.config에서 설정 읽기 (0) | 2020.09.29 |
매크로에서 무의미한 do-while 및 if-else 문을 사용하는 이유는 무엇입니까? (0) | 2020.09.29 |