后台服务不起作用Xamarin.Android



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

服务

[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();
}

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

很抱歉回答晚了,但我认为这可以帮助其他人。我想向您明确一点,您正在将此服务作为后台服务进行编写。后台服务不能长时间运行。安卓8.0之后,安卓系统中的后台服务存在一些限制。安卓系统会在一段时间后自动关闭应用程序的后台服务。

看看这个https://developer.android.com/about/versions/oreo/background

如果您想长时间运行一项服务,请使该服务前台服务。请关注https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services了解Xamarin Forms中前台服务的详细知识。

相关内容

最新更新