首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >后台服务不工作Xamarin.Android

后台服务不工作Xamarin.Android
EN

Stack Overflow用户
提问于 2015-11-09 17:23:25
回答 2查看 1K关注 0票数 5

我有问题。我的服务起作用了,但当我关闭应用程序时,服务停止了。如何让我的服务处于运行状态?

服务

代码语言:javascript
复制
[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();
}
EN

回答 2

Stack Overflow用户

发布于 2019-08-13 19:45:38

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

票数 0
EN

Stack Overflow用户

发布于 2021-06-14 19:30:39

很抱歉回答得太晚了,但我认为这对其他人有帮助。我想向您说明一点,您正在编写此服务作为后台服务。后台服务无法长时间运行。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形式获取前台服务的详细知识。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33605912

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档