Technicolor Technicolor - 9 days ago 5
Android Question

Pass data to activity started by service

I've been trying to make an alarm app using a WakefulBroadcastReceiver, which starts a wakeful service (IntentService) that starts up SecondActivity (alarm is set in MainActivity). However, I haven't been able to figure out how to pass data from MainActivity to SecondActivity, even using Intents. This is the code for setting the alarm:

Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
intent.putExtra("requestCode", 111);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 111, intent, 0);
alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(), pendingIntent);


The code for
onReceive
in AlarmReceiver:

Intent service = new Intent(context, AlarmService.class);
intent.putExtra("requestCode", intent.getIntExtra("requestCode", 222));
startWakefulService(context, service);


The code for
onHandleIntent
in AlarmService:

Context context = getApplicationContext();
Intent intent = new Intent(context, SecondActivity.class);
intent.putExtra("requestCode", intent.getIntExtra("requestCode", 333));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(intent);


Finally, in
onCreate
of SecondActivity, I have the following code:

Intent intent = getIntent();
Log.i("APP", "requestCode: " + intent.getIntExtra("requestCode", 444));


The output is
requestCode: 333
, which was the default/failsafe value in AlarmService's
onHandleIntent
(and not the original request code passed, which was 111). What am I missing?

Edit: the code for
onReceive
should be:

Intent service = new Intent(context, AlarmService.class);
service.putExtra("requestCode", intent.getIntExtra("requestCode", 222));
startWakefulService(context, service);


And that fixes the problem.

Answer
Intent intent = new Intent(context, SecondActivity.class);
intent.putExtra("requestCode", intent.getIntExtra("requestCode", 333));

You've named your new intent the same as the one your received in the service, so in the second line you're referencing not the old one, but the new - the one you're trying to initialize - this one doesn't have this extra yet, so it resolves to the default value. Change to:

Intent activityIntent = new Intent(context, SecondActivity.class); // or any other name different than 'intent'
activityIntent.putExtra("requestCode", intent.getIntExtra("requestCode", 333));

Apart from that, your code looks ok.

Comments