IntentService的onHandleIntent(意向)获得null参数意向、参数、IntentService、onHandleIntent

2023-09-07 14:54:22 作者:沉睡千年的寂寞

我使用的是IntentService运行我的Andr​​oid应用程序后台服务。奇怪的是我得到了很多的崩溃报告与情况传递给onHandleIntent意图为空。我什至不知道这怎么可能,似乎非常奇怪。任何人都可以说明为什么这可能发生?

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

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)

在我的服务文件号线466,其中空指针异常:

Line no 466 in my service file where null pointer exception:

465 protected void onHandleIntent(Intent intent) {
466                Bundle data = intent.getExtras();   

在服务启动为:

serviceIntent = new Intent(this, MyService.class);
serviceIntent.putExtra("ip", ip);
serviceIntent.putExtra("port", port);
startService(serviceIntent);                         

编辑:我现在意识到,我可能会被滥用IntentServices。当我开始了我的服务开始从onHandleIntent一些工作线程(),它继续即使onHandleIntent()返回运行。并通过结合到该服务和呼叫的成员函数/回调与线程进行通信。我会考虑使用一个更好的方式来为这个目的使用的服务,在此期间我还是不明白传递的意图如何为null。我只能怀疑Android系统的呼吁onHandleIntent对自己有一个空的意图似乎很奇怪依然。有人可以解释为什么Android系统可能会以这样的方式来调用它?

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?

推荐答案

查看Android文档IntentService.onStartCommand 。

[意图]如果其进程已经消失后,正在重新启动该服务,它已经previously返回任何东西,除了START_STICKY_COMPATIBILITY可以为null。

[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.

重新启动行为可以控制在一定程度上与 IntentService.setIntentRedelivery

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