传递的意图在 onStartCommand 中为 NULL 的原因

除了系统通过 START_STICKY这样的标志重新启动服务之外,是否还有其他原因导致传递给 onStartCommand(Intent, int, int)的意图为 NULL?

此外,当系统重新启动服务时,Intent.getAction()方法有时会返回 NULL。意图不仅仅是 getAction()

我也问了 给你,但还没有得到答复。

更新 : 在与 Mark Murphy 聊天后,他建议我在我的服务中返回 onStartCommand()回调中的 START_REDELIVER_INTENT,而不是 START_STICKY,以便在重新启动后发送整个意图。

我一开始没有这样做是因为我担心如果服务正在尝试做某事,那么在这个过程中,服务被重新启动了... ... 它会意识到它开始做那件事吗?我想这就是我需要负责的逻辑:)

27527 次浏览

I'm surprised there's no discussion of the incoming flags. I'm going to monitor this in the logs with the following:

if (null == intent || null == intent.getAction ()) {
String source = null == intent ? "intent" : "action";
Log.e (TAG, source + " was null, flags=" + flags + " bits=" + Integer.toBinaryString (flags));
return START_STICKY;
}

Update: Flags were 0 so there was nothing actionable there. I've left the null check in there with no loss of function.

Edit: Ok, I found it in the documentation of START_STICKY of all places! "if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this."

http://developer.android.com/reference/android/app/Service.html

Return START_REDELIVER_INTENT in your callback:

    public int onStartCommand(Intent intent, int flags, int startId) {


// your service code here


return android.app.Service.START_REDELIVER_INTENT; // make sure restart delivers the intent
}


It's an unexpected default, most of the time you don't want START_STICKY but START_REDELIVER_INTENT. START_REDELIVER_INTENT is the expected behavior.