gpt4 book ai didi

android - 应用程序被杀死后重启 Android Started Service

转载 作者:行者123 更新时间:2023-11-29 14:37:29 25 4
gpt4 key购买 nike

我正在尝试在 android 中执行 StartedService 以定期将用户位置发送到服务器。直到这一刻,我才设法创建服务并从“父”应用程序启动它,但我不知道如何在应用程序被杀死后让它保持 Activity 状态。根据我在互联网上发现的内容,如果“StartCommandResult.Sticky”被终止,它应该重新启动该服务,但由于某种原因,它没有重新启动。

我覆盖了 OnStartCommand:

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
locationTask = new Task(() =>
{
//stuff to do
});
locationTask.Start();
return StartCommandResult.Sticky;
}

服务是这样启动的:

    Intent intent = new Intent(this.Activity, Class.FromType(typeof(LocationService)));
this.Activity.StartService(intent);

有什么建议我应该怎么做才能在应用程序被终止后保持我的服务存活?

作为观察,我正在使用 xamarin 来做这件事,但我不介意在 android(java) 中回答。

最佳答案

official documentation 中所述:

A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.

所以,像这样启动服务

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}

即使您的应用被销毁,您的服务也会继续运行。

关于官方文档中的 Service.START_STICKY:

If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand(), but do not redeliver the last intent. Instead, the system calls onStartCommand() with a null intent, unless there were pending intents to start the service, in which case, those intents are delivered. This is suitable for media players (or similar services) that are not executing commands, but running indefinitely and waiting for a job.

关于android - 应用程序被杀死后重启 Android Started Service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28405742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com