Friendly spycrab Friendly spycrab - 2 months ago 13
Android Question

Cannot create service Xamarin

Im trying to create a media player service in xamarin but whenever i call Startservice like this

StartService(new Intent(ApplicationContext,typeof(StreamingBackgroundService)));


the onCreate method is never called. I have added the service to the androidmanifest.xml
like this

<application android:label="PlayYoutubeMP3" android:icon="@drawable/Icon"></application>


But it doesnt do anything either. I am using Android api 23 and visual studio 2017. I honestly have no idea what i am doing wrong. any help would be appreciated

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Media;

[Service(Label = "StreamingBackgroundService", Icon = "@drawable/Icon")]
public class StreamingBackgroundService : Service, SendCommand
{
private MediaPlayer player;


public override IBinder OnBind(Intent intent)
{
return null;
}


public override void OnCreate()
{
player = new MediaPlayer();
MainActivity.Event = this;
base.OnCreate();
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
//Set sticky as we are a long running operation
return StartCommandResult.Sticky;
}

public void Play()
{
player.Start();
}

private void Pause()
{
player.Pause();
}

private void Stop()
{
player.Stop();
}

public void SendCommand(Command C, object Param = null)
{
switch (C)
{
case Command.Start:
Play();
break;
case Command.Stop:
Stop();
break;
case Command.Pause:
Pause();
break;
case Command.Reset:
player.Reset();
break;
case Command.GoBack:

break;
case Command.GoForward:

break;
case Command.Initialize:
player.SetDataSource((string)Param);
player.Prepare();
player.SetWakeMode(ApplicationContext, WakeLockFlags.Partial);
break;
case Command.ShouldLoop:
player.Looping = (bool)Param;
break;
default:
break;
}
}
}
}

Answer Source

I changed it to a bound service, like SushiHangover suggested. That worked