Search code examples
androidandroid-intentandroid-serviceandroid-intentservice

Android IntentService triggered with null intent


I'm seeing a crash in Crashlytics:

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Intent.getIntExtra(java.lang.String, int)' on a null object reference at com.myapp.APKOfferQueueManagerIntentService.onHandleIntent(SourceFile:71) at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.os.HandlerThread.run(HandlerThread.java:61)

How can it be that an IntentService is being triggered with a null intent?


Solution

  • An IntentService may be stopped like every other service, but it will be restarted by "the system" until onHandleIntent() has finished its work. In this case, the documentation says the intent parameter

    ... may be null if the service is being restarted after its process has gone away

    To always get the original Intent as a parameter, use

    setIntentRedelivery(true);
    

    in the constructor of the IntentService.

    Note also that

    If multiple Intents have been sent, only the most recent one is guaranteed to be redelivered.