Xamarin.Android의 의도 서비스
시작된 서비스와 바인딩된 서비스는 모두 기본 스레드에서 실행됩니다. 즉, 성능을 원활하게 유지하려면 서비스가 비동기적으로 작업을 수행해야 합니다. 이 문제를 해결하는 가장 간단한 방법 중 하나는 작업자 큐 프로세서 패턴을 사용하는 것입니다. 여기서 수행할 작업은 단일 스레드에서 서비스되는 큐에 배치됩니다.
이 IntentService
패턴의 Android 특정 구현을 Service
제공하는 클래스의 하위 클래스입니다. 큐 작업을 관리하고, 큐를 서비스하기 위해 작업자 스레드를 시작하고, 작업자 스레드에서 실행될 큐에서 요청을 끌어온다. IntentService
큐에 더 이상 작업이 없으면 자동으로 중지되고 작업자 스레드가 제거됩니다.
작업을 만든 Intent
다음 메서드에 전달 Intent
하여 큐에 StartService
제출됩니다.
메서드 IntentService
가 작동하는 동안에는 중지하거나 중단할 OnHandleIntent
수 없습니다. 이 디자인 IntentService
으로 인해 상태 비호환 상태로 유지되어야 하며, 나머지 애플리케이션의 활성 연결 또는 통신에 의존해서는 안 됩니다. 이는 IntentService
작업 요청을 상태 비정상으로 처리하기 위한 것입니다.
서브클래싱에는 다음 두 가지 요구 사항이 있습니다.IntentService
- 새 형식(서브클래싱을
IntentService
통해 생성됨)은 메서드를 재정의합니다OnHandleIntent
. - 새 형식의 생성자에는 요청을 처리할 작업자 스레드의 이름을 지정하는 데 사용되는 문자열이 필요합니다. 이 작업자 스레드의 이름은 애플리케이션을 디버깅할 때 주로 사용됩니다.
다음 코드는 재정의된 IntentService
OnHandleIntent
메서드를 사용하는 구현을 보여줍니다.
[Service]
public class DemoIntentService: IntentService
{
public DemoIntentService () : base("DemoIntentService")
{
}
protected override void OnHandleIntent (Android.Content.Intent intent)
{
Console.WriteLine ("perform some long running work");
...
Console.WriteLine ("work complete");
}
}
작업은 해당 Intent를 IntentService
매개 변수로 사용하여 메서드를 Intent
StartService
인스턴스화한 다음 호출하여 전송됩니다. 의도는 메서드의 매개 변수 OnHandleIntent
로 서비스에 전달됩니다. 이 코드 조각은 의도에 작업 요청을 보내는 예제입니다.
// This code might be called from within an Activity, for example in an event
// handler for a button click.
Intent downloadIntent = new Intent(this, typeof(DemoIntentService));
// This is just one example of passing some values to an IntentService via the Intent:
downloadIntent.PutExtra("file_to_download", "http://www.somewhere.com/file/to/download.zip");
StartService(downloadIntent);
이 IntentService
코드 조각에 설명된 대로 의도에서 값을 추출할 수 있습니다.
protected override void OnHandleIntent (Android.Content.Intent intent)
{
string fileToDownload = intent.GetStringExtra("file_to_download");
Log.Debug("DemoIntentService", $"File to download: {fileToDownload}.");
}