【问题标题】:How to keep an IntentService running even when app is closed?即使应用程序关闭,如何保持 IntentService 运行?
【发布时间】:2023-03-13 01:20:02
【问题描述】:

在我的 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
}

}

【问题讨论】:

标签: android android-service intentservice android-intentservice


【解决方案1】:

IntentService 并非一直在运行,但它可以在 Intent 基础上运行。您发送,比如说一个要执行的命令(做某项工作),使用 Intent 和服务执行该工作并在等待其他 Intent 之后自行停止。
您应该使用通常的Service 而不是 IntentService 来实现您的目标。服务应配置为START_STICKY

【讨论】:

  • 不,我的意思不是让我的服务一直运行。我的服务需要执行长时间运行的操作。我需要做的是,即使我的应用已从最近关闭,我的服务也会继续执行该操作。完成后,它应该自行终止
  • 再次:您应该使用通常的 Service 而不是 IntentService 来实现您的目标。
  • 我要试试。谢谢!
【解决方案2】:

在你的服务类@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()

【讨论】:

  • 这真的安全吗?文档声明You should not override this method for your IntentService. Instead, override onHandleIntent(Intent), which the system calls when the IntentService receives a start request.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-26
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多