Mar 29, 2011

Pass data from activity to service

In activity:
 Intent myIntent = new Intent(MainActivity.this, MyService.class);

Bundle bundle = new Bundle();
bundle.putCharSequence("extraData", data);

pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);

Basically, it's similar to that in "Pass data between activity".

In service side, there are no getIntent().getExtras() in Service class. We can handle it in onStart() call-back method, intent will be passed as parameter.
 public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);

Bundle bundle = intent.getExtras();
data = (String) bundle.getCharSequence("extraData");
smsTextToSend = (String) bundle.getCharSequence("extraSmsText");


  1. And how can i do to call the function onStart? I execute a Service from Activity using startService()

  2. onStart() is a call-back function, the system will call it on service start. You just need to override it.

    To simplify the job, Eclipse can help:
    - Right click on any empty space on your service code.
    - click Source
    - click Override/Implement Methods...
    - Search and enable onStart method, and click OK.
    - Eclipse will insert the dummy method, you just need to fill in your code.

  3. This comment has been removed by the author.

  4. Thank you!! I'm doing the tests.. =) You've got a good blog.. i work with android and i'm very interested.. I'm following you =P

  5. how about passing data from service to activity ?

  6. how i pass the data from service to activity???


Infolinks In Text Ads