I have created a service that is called from the main activity and passing it a simple variable to access and toast to the screen from inside the service. I can't seem to find the right code to access the variable from inside the service. Any help would be greatly appreciated. Thanks.
Main Activity calling the service from inside a button click listener:
@Override
public void onClick(View v) {
Intent eSendIntent = new Intent(getApplicationContext(), eSendService.class);
eSendIntent.putExtra("extraData", "somedata");
startService(eSendIntent);
}
eSendService service class code:
public class eSendService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
// This is the code that I am struggling with. Not sure how to access the
// variable that was set in the intent. Please advise.
// The below code gives the following error in eclipse:
// The method getIntent() is undefined for the type eSendService
Bundle extras = getIntent().getExtras();
}
}
Again, thanks for any and all help. I just can't seem to find a simple example out there that shows me how to do this. Thanks.
Ok, found my own answer finally and want to share it to help anyone else.
The answer: onStart() or onStartCommand() (which one depends on target api) are what the intent is passed to and called after startService() is called by the activity. I thought the intent was passed to the onCreate() method but it is actually passed to the start command for services.
@Override public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
String extras; extras = intent.getExtras().getString("extraData");
Toast.makeText(this, extras, Toast.LENGTH_LONG).show();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With