Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how to get the intent received by a service?

I'm starting a service with an intent where I put extra information.

How can I get the intent in the code of my service?

There isn't a function like getIntent().getExtras() in service like in activity.

like image 741
BuzBuza Avatar asked Dec 27 '09 02:12

BuzBuza


People also ask

How do I get intent in service?

Intent ir=new Intent(this, Service. class); ir. putExtra("data", data); this. startService(ir);

How does intent service work in Android?

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent, in turn, using a worker thread, and stops itself when it runs out of work.


3 Answers

Override onStart() -- you receive the Intent as a parameter.

like image 44
CommonsWare Avatar answered Oct 16 '22 16:10

CommonsWare


onStart() is deprecated now. You should use onStartCommand(Intent, int, int) instead.

like image 92
Alagu Avatar answered Oct 16 '22 17:10

Alagu


To pass the extras:

Intent intent = new Intent(this, MyService.class);
intent.putExtra(MyService.NAME, name);
...
startService(intent);

To retrieve the extras in the service:

public class MyService extends Service {  
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        String name = intent.getExtras().getString(NAME);
        ...
    } 
    ...
} 
like image 4
David Miguel Avatar answered Oct 16 '22 18:10

David Miguel