Android: retrieving an extra from intent in servic

2019-07-31 17:30发布

问题:

So I'm starting a service with a putExtra integer value that I want to pass along:

        Intent i = new Intent(context, clickService.class); 
        i.putExtra("numClicks", thisNumClicks); 
        context.startService(i);

And this starts the service. The question is how do I retrieve this value back whilst in the service? Here's what I tried that I remember using in a previous project (from an activity):

int result = getIntent().getExtras().getInt("numClicks");

However getIntent() is not defined for services I guess? What do I use then?

Thanks.

回答1:

From the docs for Context.startService(Intent service)

Every call to this method will result in a corresponding call to the target service's onStartCommand(Intent, int, int) method, with the intent given here.

So basically just use the Intent passed to onStartCommand(...).