【问题标题】:Background service not work Xamarin.Android后台服务不起作用 Xamarin.Android
【发布时间】:2016-02-09 21:49:19
【问题描述】:

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

服务

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

【问题讨论】:

    标签: c# android xamarin


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      很抱歉回答迟了,但我认为它可以帮助其他人。我想向您说明一下,您正在将此服务编写为后台服务。后台服务不能长时间运行。 Android 8.0 之后的 Android 后台服务有一些限制。 Android 会在一段时间后自动终止应用的后台服务。

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

      如果你想长时间运行一个服务,那就做服务前台服务。请关注https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services,详细了解 Xamarin Forms 中的前台服务。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多