【问题标题】:Can't get my android service working if my app closes如果我的应用关闭,我的 android 服务无法正常工作
【发布时间】:2018-02-09 20:59:56
【问题描述】:

大家好,我在测试中遇到了这个问题,我一直在寻找信息,但目前找不到任何解决方案。我遵循了服务指南,并按照指南所说的做了,但仍然遇到问题。
我的服务代码:

    [Service(Label="MyService")]
    public class MyService : Service{

        protected override StartCommandResult onStartCommand(Intent intent, StartCommandFlags flags, int startId){
            var t = new Task(() => {
                Looper.prepare();
                    do{
                        DoServiceWork();
                    while(running);
            });

            t.Start();

            return StartCommandResult.Sticky;
        }
    }

在我的主要活动中:

protected override void OnCreate(Bundle bundle){
    new Task(StartService).Start();
}

void StartService(){
    var intent = new Intent(Application.Context, typeof(MyService));
    Application.Context.StartService(intent);
}

当我的应用程序被杀死时,我无法让我的服务继续工作,我希望你们能帮助我解决这个问题,提前感谢那些可以帮助我的人。

【问题讨论】:

  • 您是否在清单中注册了您的服务?
  • @codeMagic,感谢您的指导,将删除。我想也许,我们需要看到一条错误消息。
  • @Daniel 没问题。但是,如果您认为我错过了一些错误,请随时添加。我不是总是对;)
  • @ChrisStillwell 当你用服务属性装饰服务类时,它会自动注册,

标签: android service xamarin.forms android-service background-service


【解决方案1】:

当我的应用被终止时,我无法让我的服务继续工作

请参考this,在这篇文章中,你可以找到:

请注意,服务与其他应用程序对象一样,在其托管进程的主线程中运行。

“服务在主线程中运行”,这意味着如果你的应用程序/主进程/主线程被杀死,你的服务将被杀死。如果您希望您的服务运行,您的应用程序必须处于活动状态。没有任何自定义服务可以始终运行。

您可以使用IntentService进行重量级计算,同时会提高您的应用程序的优先级,使您的应用程序不会被杀死。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多