I develop a StepCounter application with Xamarin.Android.
What do I have for now:
1) In MainActivity in OnCreate() I call
StartService(new Intent(this, typeof(MyService)));
Then in OnStart() I call BindService(serviceIntent, MyServiceConnection, Bind.AutoCreate);
2) That gives me a nice service which is 1) foreground 2) both StartService and BindService 3) returns StartCommandResult.Sticky in OnStartCommand()
3) In MyService I register MainActivity as a listener for every detected step. I use Interface as suggested here and the UI in MainActivity updates in real time, everything works perfect.
But there is a problem.
When I swipe MainActivity from recent tasks my app supposed to shut down/finish/going off and so it does.
But MyService is STICKY so it starts again and the user can see a notification in status bar. That's exactly what I want. Sticky undying service.
And than first scenario: user presses the notification -> that creates an activity -> OnStart() provides binding to MyService again -> works ok.
Second scenario: user does not press the notification -> no activity has been created (it's the only service) -> user makes some steps -> application fails.
I don't know how to handle this second kind of behavior.
Maybe that is because I register MainActivity as a listener? And if I destroy it there is nothing to update My service? In OnStop() I call UnbindService(MyService); and I expect that MyService can work even without activity. But obviously, I do something wrong.
Any help is appreciated.
UPD: Find the solution, see my answer below.