How to start Android Service from dependency class?

NorbertKNorbertK PLMember
edited January 2017 in Xamarin.Android

Hi

As in the title. I have PCL project. What if I want some common functionality to be accomplished by android service?

I tried:

public class DeviceDependentMethods : iDeviceDependentMethods { public void StartDemoService() { Application.Context.StartService(new Android.Content.Intent(Application.Context.ApplicationContext, typeof(DemoService))); } }

[Service(Name = "myname.demoservice")]
public class DemoService : Android.App.Service
{
        public override void OnCreate()
        {
            MyLogger.Log("Service created"); // this code is executed

            base.OnCreate(); // here exception is thrown and application stops
        }
}

Can anyone help me with this issue?

Answers

  • D3nnisD3nnis USUniversity ✭✭✭
    edited January 2017

    Try to use OnStartCommand() instead of OnCreate().

        public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId)     {
            MyLogger.Log("Service created");
            return StartCommandResult.Sticky;
        }
    

    StartCommandResult.Sticky; will keep the service alive.

  • NorbertKNorbertK PLMember

    @D3nnis said:
    Try to use OnStartCommand() instead of OnCreate().

      public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId)     {
          MyLogger.Log("Service created");
          return StartCommandResult.Sticky;
      }
    

    StartCommandResult.Sticky; will keep the service alive.

    Result is the same: log is made, but then I got NullReferenceException.

  • AbhiVazeAbhiVaze Member ✭✭

    I used
    Forms.Context.StartService(new Intent(Forms.Context,typeOf(MyService));

    This doesn't raises exception, but the log I've written inside OnStartCommand() doesn't work.
    So I think service isn't getting started....

Sign In or Register to comment.