无法创建服务Xamarin

时间:2017-08-11 17:34:03

标签: android xamarin service xamarin.android

我试图在xamarin中创建一个媒体播放器服务,但每当我打电话给这样的Startservice时

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

永远不会调用onCreate方法。我已将服务添加到androidmanifest.xml中 像这样

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

但它也没有做任何事情。我正在使用Android api 23和视觉工作室2017.老实说,我不知道我做错了什么。任何帮助将不胜感激

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;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我把它改成了绑定服务,就像SushiHangover建议的那样。这工作