정상적으로 작동하는 다음 코드는 갑자기 아래 메시지를 두 번 잘못 print합니다.
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
}
}
앱이 다시 시작되면 아래와 같이 메시지가 한 번 print됩니다.
MainApplicationService started
MyMessagemessage received
Xamarin Android, Android Lollipop