关于 START_STICKY 的服务

About START_STICKY in Service

关于在 Android 服务中使用 START_STICKY

官方文档说:

if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance;

这是可以理解的,所以当启动服务的进程由于内存不足而被杀死时,OS稍后会自动尝试再次启动该服务。

我的问题是,如果我的代码启动服务 startService(...),然后停止它(例如,我的应用 UI 上有一个 "STOP" 按钮,按下它时,我call stopService(...)), 系统稍后会再次启动该服务吗?或者服务实例会完全从内存中清除,而无需稍后由系统创建? (此场景没有服务绑定)

我在测试期间在我的应用程序中使用了 stopService() 按钮。使用命令停止它后,它不会再次启动,直到您调用 startService().

START_STICKY- 告诉系统在从低内存中恢复后,当有足够的内存可用时,创建服务的新副本。在这里您将丢失之前可能已经计算出的结果。

您的查询的答案是,只有在使用 START_STICKY 时在任何情况下被 OS 杀死的服务才会重新创建。如果我们要终止服务,为什么 android 需要重现它 again.if 你使用 stopSelf() 即使它是粘性的,服务也不会重新创建。

Android 不时终止进程。但是 android 系统会自动重新创建粘性服务。有人告诉我们,Sticky 服务被销毁并在 5 秒后重新创建。

START_STICKY是启动服务的运行方式,取决于它们的值return来自于StartCommand() method.START_STICKY用于创建服务副本的服务但是它不会存储之前执行的任何服务结果。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Logs.d(TAG, "# Service - onStartCommand() starts here");

// If service returns START_STICKY, android restarts service automatically after forced close.
// At this time, onStartCommand() method in service must handle null intent.
return Service.START_STICKY;

}