Saturday, July 21, 2012

Pass data from activity to service in andorid

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");

No comments:

Post a Comment