我有以下代码
@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”变量不为null,我正在检查上面。如果是这种情况,请执行以下代码。但我仍然有nullpointerexception。
服务是从以下活动开始的:
startService(new Intent(this, MainService.class));
我做错了什么?
答案 0 :(得分:12)
您收到NullPointerException
,因为intent.getAction()
似乎返回null
。
您应该将支票延伸至:
if(intent != null && intent.getAction() != null) {
如果您想为意图添加动作,则需要致电setAction():
Intent i = new Intent(this, MainService.class);
i.setAction("foo");
startService(i);
答案 1 :(得分:0)
我得到了类似的堆栈,添加了支票
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