잡동사니

반응형

질문

정상적으로 작동하는 다음 코드는 갑자기 아래 메시지를 두 번 잘못 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


답변1

메모리 부족으로 인해 시스템이 서비스를 파괴 할 수 있으며,이 경우 시스템은 가능한 한 빨리 서비스를 재 구축합니다. 다음과 같이 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;
    }


 

 

 

 

출처 : https://stackoverflow.com/questions/61314129/android-service-called-two-times-wrongly-with-one-startservice-method

반응형

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band