Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intent always null onStartCommand

I have 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 NullPointerException on line:

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

Why? I'm checking above if "intent" variable is not null. If that's the case execute following code. But i still got nullpointerexception.

Service is started from activity like that:

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

What am I doing wrong?

like image 551
Firefoxx Pwnass Avatar asked Apr 16 '13 17:04

Firefoxx Pwnass


1 Answers

You are getting a NullPointerException because intent.getAction() seems to return null.

You should extend your check to this:

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);
like image 154
rekire Avatar answered Nov 13 '22 04:11

rekire