Следующий код, который работает нормально, неожиданно неправильно печатает приведенное ниже сообщение два раза:
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 Леденец