后台服务不工作 Xamarin.Android

Vun*_*nda 5 c# android xamarin

我有问题。我的服务有效,但是当我关闭应用程序服务时停止了。我如何才能让我的服务运行?

服务

[Service]
public class NotificationService : Service
{
  public NotificationService () { }

  public override StartCommandResult OnStartCommand (Android.Content.Intent intent, StartCommandFlags flags, int startId)
  {
    new Task(() =>
        {
            DoWork();
        } ).Start();
    return StartCommandResult.Sticky;
  }

public override void OnDestroy ()
{
    base.OnDestroy ();
}

  public override IBinder OnBind (Intent intent)
  {
    throw new NotImplementedException ();
  }

  void DoWork()
  {
    new Task(() =>
        {
            for (int i = 0; i < 100; i ++)
            {
                System.Threading.Thread.Sleep(1000);
                var context = Android.App.Application.Context;
                var builder = new Android.App.Notification.Builder(context)
                    .SetSmallIcon(Resource.Drawable.icon)
                    .SetContentTitle("My application")
                    .SetDefaults(NotificationDefaults.Sound)
                    .SetContentText(i.ToString())
                    .SetOngoing(true);
                var not = builder.Build();
                var notManager = context.GetSystemService(NotificationService) as NotificationManager;
                notManager.Notify(1, not);
            }
        }).Start();
    }
}

MainActivity.cs

protected override void OnCreate (Bundle bundle)
{
    base.OnCreate (bundle);

    global::Xamarin.Forms.Forms.Init (this, bundle);

    LoadApplication (new App ());

    new Task(() =>
        {
            var notificationIntent = new Intent(this, typeof(NotificationService));
            StartService(notificationIntent);
        }).Start(); 
    Android.Widget.Toast.MakeText(this, "run", Android.Widget.ToastLength.Short).Show();
}
Run Code Online (Sandbox Code Playgroud)

Vun*_*nda 0

当我们从VS启动应用程序并停止应用程序时。VS自动关闭所有服务。需要将应用程序构建到设备上,然后从设备启动应用程序。