Intention is always null onStartCommand

I have the following code

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

but it always returns NullPointerExceptionin a string:

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

Why? I check above if the intent variable is not zero. If this case executes the following code. But I still had a nullpointer exception.

The service starts from this activity:

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

What am I doing wrong?

+5
source share
1 answer

You get NullPointerExceptionit because it intent.getAction()seems to be returning null.

You should expand your check to the following:

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

If you want to add an action to your intent, you need to call setAction () :

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

All Articles