Intent始终为null onStartCommand

Fir*_*ass 5 service android android-intent android-activity

我有以下代码

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

但它总是在线返回NullPointerException:

Log.i("INTENT", intent.getAction().toString());
Run Code Online (Sandbox Code Playgroud)

为什么?如果"intent"变量不为null,我正在检查上面.如果是这种情况,请执行以下代码.但我仍然有nullpointerexception.

服务从以下活动开始:

startService(new Intent(this, MainService.class));
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

rek*_*ire 13

你得到一个NullPointerException因为intent.getAction()好像回来了null.

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

if(intent != null && intent.getAction() != null) {
Run Code Online (Sandbox Code Playgroud)

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

Intent i = new Intent(this, MainService.class);
i.setAction("foo");
startService(i);
Run Code Online (Sandbox Code Playgroud)