以下正常工作的代码突然错误地在下面两次打印了该消息:
MainApplicationService started
MyMessagemessage received
MainApplicationService started
MyMessagemessage received
下面的代码:
[Activity(Label = "My app", MainLauncher = true, Name = "com.myapp.StartupActivity")]
public class StartupActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Intent serviceIntent = new Intent(this, typeof(MainApplicationService));
StartService(serviceIntent);
Finish();
}
}
[Service(Name = "com.myapp.MainApplicationService", Label = "Main Application Service", Exported = false)]
public class MainApplicationService : Service
{
private IDeviceLog _logger;
public override IBinder OnBind(Intent intent)
{
return null;
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
_logger = Ioc.Container.Resolve<IDeviceLog>();
_logger.Info("MainApplicationService started");
var worker = Ioc.Container.Resolve<IWorker>();
Task.Run(async () => await worker.Init());
return StartCommandResult.Sticky;
}
}
public class Worker:IWorker {
private async Task Init(){
_deviceLog.Info($"{nameof(MyMessagemessage)} received"); //called two times wrongly
}
}
重新启动应用程序后,消息打印一次,如下所示
MainApplicationService started
MyMessagemessage received
Xamarin Android,Android Lollipop
系统可能由于内存不足而破坏服务,如果发生这种情况,系统将尽快重建服务。您可以在OnStartCommand
中为服务定义状态,例如:
private bool isStarted;
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
if (isStarted)
{
// service is already started
}
else
{
_logger = Ioc.Container.Resolve<IDeviceLog>();
_logger.Info("MainApplicationService started");
var worker = Ioc.Container.Resolve<IWorker>();
Task.Run(async () => await worker.Init());
isStarted = true;
}
return StartCommandResult.Sticky;
}