Pass data from Activity to Service using an Intent
Solution 1
First Context (can be Activity/Service etc)
For Service, you need to override onStartCommand there you have direct access to intent
:
Override
public int onStartCommand(Intent intent, int flags, int startId) {
You have a few options:
1) Use the Bundle from the Intent:
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);
2) Create a new Bundle
Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);
3) Use the putExtra() shortcut method of the Intent
Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);
New Context (can be Activity/Service etc)
Intent myIntent = getIntent(); // this getter is just for example purpose, can differ
if (myIntent !=null && myIntent.getExtras()!=null)
String value = myIntent.getExtras().getString(key);
}
NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.
Solution 2
For a precise answer to this question on "How to send data via intent from an Activity to Service", Is that you have to override the onStartCommand()
method which is where you receive the intent object:
When you create a Service
you should override the onStartCommand()
method so if you closely look at the signature below, this is where you receive the intent
object which is passed to it:
public int onStartCommand(Intent intent, int flags, int startId)
So from an activity you will create the intent object to start service and then you place your data inside the intent object for example you want to pass a UserID
from Activity
to Service
:
Intent serviceIntent = new Intent(YourService.class.getName())
serviceIntent.putExtra("UserID", "123456");
context.startService(serviceIntent);
When the service is started its onStartCommand()
method will be called so in this method you can retrieve the value (UserID) from the intent object for example
public int onStartCommand (Intent intent, int flags, int startId) {
String userID = intent.getStringExtra("UserID");
return START_STICKY;
}
Note: the above answer specifies to get an Intent with getIntent()
method which is not correct in context of a service
Solution 3
If you bind your service, you will get the Extra in onBind(Intent intent)
.
Activity:
Intent intent = new Intent(this, LocationService.class);
intent.putExtra("tour_name", mTourName);
bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
Service:
@Override
public IBinder onBind(Intent intent) {
mTourName = intent.getStringExtra("tour_name");
return mBinder;
}
Solution 4
Another posibility is using intent.getAction:
In Service:
public class SampleService inherits Service{
static final String ACTION_START = "com.yourcompany.yourapp.SampleService.ACTION_START";
static final String ACTION_DO_SOMETHING_1 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_1";
static final String ACTION_DO_SOMETHING_2 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_2";
static final String ACTION_STOP_SERVICE = "com.yourcompany.yourapp.SampleService.STOP_SERVICE";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
//System.out.println("ACTION: "+action);
switch (action){
case ACTION_START:
startingService(intent.getIntExtra("valueStart",0));
break;
case ACTION_DO_SOMETHING_1:
int value1,value2;
value1=intent.getIntExtra("value1",0);
value2=intent.getIntExtra("value2",0);
doSomething1(value1,value2);
break;
case ACTION_DO_SOMETHING_2:
value1=intent.getIntExtra("value1",0);
value2=intent.getIntExtra("value2",0);
doSomething2(value1,value2);
break;
case ACTION_STOP_SERVICE:
stopService();
break;
}
return START_STICKY;
}
public void startingService(int value){
//calling when start
}
public void doSomething1(int value1, int value2){
//...
}
public void doSomething2(int value1, int value2){
//...
}
public void stopService(){
//...destroy/release objects
stopself();
}
}
In Activity:
public void startService(int value){
Intent myIntent = new Intent(SampleService.ACTION_START);
myIntent.putExtra("valueStart",value);
startService(myIntent);
}
public void serviceDoSomething1(int value1, int value2){
Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_1);
myIntent.putExtra("value1",value1);
myIntent.putExtra("value2",value2);
startService(myIntent);
}
public void serviceDoSomething2(int value1, int value2){
Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_2);
myIntent.putExtra("value1",value1);
myIntent.putExtra("value2",value2);
startService(myIntent);
}
public void endService(){
Intent myIntent = new Intent(SampleService.STOP_SERVICE);
startService(myIntent);
}
Finally, In Manifest file:
<service android:name=".SampleService">
<intent-filter>
<action android:name="com.yourcompany.yourapp.SampleService.ACTION_START"/>
<action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_1"/>
<action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_2"/>
<action android:name="com.yourcompany.yourapp.SampleService.STOP_SERVICE"/>
</intent-filter>
</service>
Solution 5
Pass data from Activity to IntentService
This is how I pass data from Activity
to IntentService
.
One of my application has this scenario.
MusicActivity ------url(String)------> DownloadSongService
1) Send Data (Activity code)
Intent intent = new Intent(MusicActivity.class, DownloadSongService.class);
String songUrl = "something";
intent.putExtra(YOUR_KEY_SONG_NAME, songUrl);
startService(intent);
2) Get data in Service (IntentService code)
You can access the intent in the onHandleIntent()
method
public class DownloadSongService extends IntentService {
@Override
protected void onHandleIntent(@Nullable Intent intent) {
String songUrl = intent.getStringExtra("YOUR_KEY_SONG_NAME");
// Download File logic
}
}
Related videos on Youtube
GobiasKoffi
Updated on July 05, 2022Comments
-
GobiasKoffi almost 2 years
How do I get data within an Android
Service
that was passed from an invokingActivity
? -
Chanaka udaya about 11 yearsBut we can't use getIntent() method inside a service. How can achieve this when we are sending value from activity to service?
-
zeeshan almost 10 yearsThis should have been the accepted answer. The accepted answer is wrong for Service.
-
fullOfQuestion almost 8 yearsI have this error :
Unable to start service Intent: not found
-
Neelay Srivastava over 7 yearsjust use intent no getIntent() is required
-
oshurmamadov almost 7 yearsYou are starting the service multiple times...does that mean multiple instances of the same service wil be created every time ?
-
Carlos Gómez almost 7 yearsServices have singleton pattern. stackoverflow.com/questions/2518238/…
-
Martin Pfeffer almost 7 years@ChefPharaoh that's a good question. Try to log the intent's values.
Arrays.toString(yourAry[])
will help you here. -
Chef Pharaoh almost 7 yearsSince I wanted to pass a custom class I figured out I just had to implement the parcelable interface and the it was all good. Thanks though.
-
Marian Paździoch over 6 years"switch (action)" action can be null
-
Carlos Gómez over 6 yearsNot in my code: The service is always called using a method. In any case, it's a simple code to explain how to do it. In a real program, you always have to check these things and also if the parameters arrive with the appropriate values
-
NoHarmDan over 4 yearsThis should not be the accepted answer, as this is not the correct solution for services.
-
DikShU over 2 yearsgetintent is now depricated
-
Lavnish Chaudhary about 2 yearsHow do I send an intent to the service after service has started?