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.