Xamarin.Android 中的意向服务
启动和绑定服务都在main线程上运行,这意味着要保持性能顺畅,服务需要异步执行工作。 解决此问题的最简单方法之一是 使用工作线程队列处理器模式,其中要完成的工作放置在由单个线程提供服务的队列中。
是 IntentService
类的 Service
子类,提供此模式的特定于 Android 的实现。 它将管理排队工作、启动工作线程来为队列提供服务,以及从队列拉取请求以在工作线程上运行。 IntentService
当队列中没有更多工作时,会悄然停止自身并删除工作线程。
通过创建 , Intent
然后将其传递给 Intent
方法,将工时提交到 StartService
队列。
在方法工作时,无法停止或中断 OnHandleIntent
该方法 IntentService
。 由于这种设计, 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
,然后使用该意向作为参数调用 StartService
方法,将工作发送到 IntentService
。 意向将作为 方法中的 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}.");
}