IntentService’s onHandleIntent(Intent) gets null argument

IntentService’s onHandleIntent(Intent) gets null argument

I’m using an IntentService to run a background service for my app on android. Oddly I’m getting a lot of crash reports with cases where the intent passed to onHandleIntent is null. I’m not even sure how this is possible and seems extremely odd. Can anyone suggest why this might be happening?
at com.example.MyService.onHandleIntent(
at android.os.Handler.dispatchMessage(
at android.os.Looper.loop(

Line no 466 in my service file where null pointer exception:
465 protected void onHandleIntent(Intent intent) {
466 Bundle data = intent.getExtras();

The service is started as:
serviceIntent = new Intent(this, MyService.class);
serviceIntent.putExtra(“ip”, ip);
serviceIntent.putExtra(“port”, port);

I realise now that I might be misusing IntentServices. When I start the service I start off some worker threads from onHandleIntent() which continue running even after onHandleIntent() returns. And communicate with the threads by binding to the service and calling member functions/callbacks.
I will look into using a better way to use services for this purpose, in the meanwhile I still don’t understand how the intent being passed is null. I can only suspect that the Android system is calling onHandleIntent on its own with a null intent which seems odd still. Can someone explain why the android system might be calling it in such a way?

Related:  How to convert a color integer to a hex String in Android?


Solution 1:

See the Android documentation for IntentService.onStartCommand.

[The intent] may be null if the service is being restarted after its process has gone away, and it had previously returned anything except START_STICKY_COMPATIBILITY.

The restart behavior can be controlled to some degree with IntentService.setIntentRedelivery

Solution 2:

I was also getting null Intent inside onHandleIntent. And the reason was I was passing parcelable object inside that intent. I couldn’t understand reason, but I got it working after not passing parcelable object.