在onTaskRemoved之后再次创建服务

Mar*_*cel 5 service android android-activity

我做了一个远程服务,这个服务是在第一次启动时由我的活动启动的,之后,活动总是查看服务是否已启动以避免再次启动它.

该服务在onCreate函数中运行一些方法.此服务始终在运行并在启动时启动.

问题(不是一个大问题,但我想知道为什么)是一旦创建服务,如果我停止我的活动调用onTaskRemoved,这是正确的,但几秒后再次调用oncreate方法,服务启动再次.

知道为什么吗?我该如何控制呢?

<service
        android:name=".Service"
        android:icon="@drawable/ic_launcher"
        android:label="@string/service_name"
        android:process=":update_process" >
</service>
Run Code Online (Sandbox Code Playgroud)

AndroidManifest.xml中

if (!isRunning()) {
    Intent service = new Intent(this, UpdateService.class);
    startService(service);
} else {
    //Just to debug, comment it later
    Toast.makeText(this, "Service was running", Toast.LENGTH_SHORT).show();
}
Run Code Online (Sandbox Code Playgroud)

如果服务未运行,则启动该服务

Bja*_*sen 8

问题是你的服务默认是粘性的,这意味着它会在被杀死时重新启动,直到你明确要求它被停止.

覆盖onStartCommand()服务中的方法,并让它返回START_NOT_STICKY.然后你的服务将不会被杀死时重新启动.

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    return START_NOT_STICKY;
}
Run Code Online (Sandbox Code Playgroud)


Tux*_*ude 6

虽然Bjarke的解决方案是有效的,但我想提出一个替代解决方案,其中包含可能需要在服务中执行任何恢复的情况.

Android onStartCommand()在重新启动服务后再次调用,以通知您服务进程意外崩溃(因为其任务堆栈已被删除),现在正在重新启动.

如果您查看intent参数onCreate(),它将null(仅适用于此类重新启动),这表示Android正在重新创建以前粘性服务,该服务意外崩溃.

在某些情况下,最好NON_STICKY只返回此类重新启动,执行任何所需的清理/恢复并停止服务,以便您正常退出.

当服务正常启动时,您仍然应该返回,STICKY否则您的服务将永远不会重新启动以允许您执行任何恢复.

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    // intent is null only when the Service crashed previously
    if (intent == null) {
        cleanupAndStopServiceRightAway();
        return START_NOT_STICKY;
    }
    return START_STICKY;
}

private void cleanupAndStopServiceRightAway() {
        // Add your code here to cleanup the service

        // Add your code to perform any recovery required
        // for recovering from your previous crash

        // Request to stop the service right away at the end
        stopSelf();
}
Run Code Online (Sandbox Code Playgroud)

另一个选择是请求停止(使用stopSelf())您的服务作为一部分,onTaskRemoved()以便Android甚至不必首先杀死该服务.