问题
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?
STACK_TRACE
java.lang.NullPointerException
at com.example.MyService.onHandleIntent(MyService.java:466)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)
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);
startService(serviceIntent);
Edit: 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?
回答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
回答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.
来源:https://stackoverflow.com/questions/22309582/intentservices-onhandleintentintent-gets-null-argument