如何在应用程序关闭时保持 IntentService 运行?

How to keep an IntentService running even when app is closed?

在我的 Android 应用程序中,我通过调用

从 Activity 中启动 IntentService
startService(new Intent(this, MyService.class));

它就像一个魅力。我可以在 Activies 之间移动,按 Home 按钮切换到其他应用程序……它仍然有效。但是,如果我从最近屏幕上删除我的应用程序,我的服务就会停止。我怎样才能避免这种情况?换句话说,即使我的应用程序因最近的应用程序而关闭,我如何才能保持服务 运行?

我的服务代码如下:

public class MyService extends IntentService {

public MyService() {
    super("MyService");
}

@Override
protected void onHandleIntent(Intent intent) {
    //Here I run a loop which takes some time to finish
}

}

IntentService 并非始终 运行 但它适用于 Intent 基础。你发送,假设一个命令来做(做一些工作),使用 Intent 和服务执行该工作并在等待其他 Intent 之后自行停止。
您应该使用通常的 Service 而不是 IntentService 来实现您的目标。服务应配置为 START_STICKY.

在你的服务中class@OverrideonStartCommand方法

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

要终止服务本身,您可以使用stopSelf()