Intent始终为null onStartCommand

我有以下代码

@Override public int onStartCommand(Intent intent, int flags, int startId) { if(intent != null) { Log.i("INTENT", intent.getAction().toString()); } return START_STICKY; } 

但它总是在线返回NullPointerException

 Log.i("INTENT", intent.getAction().toString()); 

为什么? 我在上面检查“intent”variables是否为空。 如果是这种情况,请执行以下代码。 但我仍然有nullpointerexception。

服务从以下活动开始:

 startService(new Intent(this, MainService.class)); 

我究竟做错了什么?

您收到NullPointerException因为intent.getAction()似乎返回null

你应该把支票延伸到这个:

 if(intent != null && intent.getAction() != null) { 

如果要在意图中添加Action,则需要调用setAction() :

 Intent i = new Intent(this, MainService.class); i.setAction("foo"); startService(i); 

我得到了类似的堆栈,添加支票

 intent.getAction() != null 

有效。

 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.languoguang.welcomeapp, PID: 17676 java.lang.RuntimeException: Unable to start service com.example.languoguang.welcomeapp.CountService@f6049d4 with Intent { cmp=com.example.languoguang.welcomeapp/.CountService }: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3698) at android.app.ActivityThread.access$1500(ActivityThread.java:198) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1668) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6649) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference at com.example.languoguang.welcomeapp.CountService.onStartCommand(CountService.java:24) at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3679) at android.app.ActivityThread.access$1500(ActivityThread.java:198) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1668) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6649) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826) 

I /处理:发送信号。 PID:17676 SIG:9