终止启动粘性服务的 activity 也会终止该服务

Killing an activity that started a sticky service kills the service too

我正在使用一个空 activity 来启动粘性服务。我使用以下代码启动服务。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent service = new Intent(this, MyService.class);
    service.setAction("com.company.test.MyService");
    startService(service);
    finish();
    setContentView(R.layout.activity_transparent);
}

问题是,如果 activity 被终止,将导致服务重新启动。有没有办法避免这个问题?

注意:我通过将应用程序从任务管理器中滑出来终止应用程序,而不是 activity 的 finish() 调用。

不,实际上。这是 Android SDK 中的一项新功能 - 终止应用程序会终止连接到该应用程序的 所有 进程,甚至应用程序的粘性服务也不会再重新启动。(编辑:服务 可能 不会重新启动,具体取决于设备;显然,粘性服务在某些版本的 android 上仍然是一个错误功能。)

如果您想 运行 永久保持您的服务,您将需要使用 ForegroundService,并在抽屉中持久通知。

显然,这是为了确保没有用户不知情的服务运行。