Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling getIntent Method in service

Tags:

I have to pass parameter from MyActivity.class to TestService.class. MyActivity is a Activity class and TestService is a Service that I have made for sending messages. I have to pass parameter from Activity to the Service, but when I call Intent i = getIntent(); in service class, I am getting an error getIntent() is undefined.

So, how can I send parameters from my Activity to Service?

like image 268
CodingDecoding Avatar asked Aug 14 '12 09:08

CodingDecoding


People also ask

How do I use Getintent in service on Android?

Start your service like this; Intent ir=new Intent(this, Service. class); ir. putExtra("data", data); this.

How do you call a service method?

You can call startService(intent) and bindService(mIntent, mConnection, BIND_AUTO_CREATE) in any order. Binding and Starting a service are two independent things.


1 Answers

Start your service like this;

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

You attach your data as an intent extra.

Then to retrieve the data from the service;

data=(String) intent.getExtras().get("data");  

So you can access your parameter from either the onHandleIntent or onStartCommand Intent parameter. (depending on which type of service you are running) For Example;

Service

protected void onStartCommand (Intent intent, int flags, int startId) {     data=(String) intent.getExtras().get("data");  } 

public int onStartCommand (Intent intent, int flags, int startId)

IntentService

protected void onHandleIntent(Intent intent) {     data=(String) intent.getExtras().get("data");  } 

protected abstract void onHandleIntent (Intent intent)

like image 104
Lunar Avatar answered Oct 05 '22 05:10

Lunar