As I already suggested in the comments section something like the following may be a solution.
This approach requieres four classes:
- A
BootBroadcastReceiver.class
whichextends BroadcastReceiver
to listen to the onBootCompleted broadcast. As soon as the boot is completed this class will start theAlarmStarterService.class
. - The
AlarmStarterService.class
whichextends Service
will start both alarms then. - The
AlarmBroadcastReceiver.class
which alsoextends BroadcastReceiver
will receive the broadcasts fired by the alarms and then start theShowNotificationService.class
and passing the ID to it through theIntent
. - And finally the
ShowNotificationService.class
which alsoextends Service
and will show a notification based on the ID passed trough theIntent
.
The BootBroadcastReceiver may look like this.
public class BootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, AlarmStarterService.class));
}
}
public class AlarmStarterService extends Service {
public static final int REQUEST_CODE_DAILY = 10000;
public static final int REQUEST_CODE_MONTHLY = 10001;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
createAlarm();
stopSelf();
}
private void createAlarm() {
PendingIntent pIntentDaily = getPendingIntent(REQUEST_CODE_DAILY);
PendingIntent pIntentMonthly = getPendingIntent(REQUEST_CODE_MONTHLY);
AlarmManager am = (AlarmManager) this
.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC, TIME_DESIRED, AlarmManager.INTERVAL_DAY, pIntentDaily);
am.setRepeating(AlarmManager.RTC, TIME_DESIRED, AlarmManager.INTERVAL_DAY * 30, pIntentMonthly );
}
private PendingIntent getPendingIntent(int requestCode) {
Intent i= new Intent(this, AlarmBroadcastReceiver.class);
i.putExtra("_id", requestCode);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return PendingIntent.getBroadcast(this, requestCode, i, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
public class AlarmBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, ShowNotificationService.class)
.putExtra("_id", intent.getIntExtra("_id", -1)));
}
}
public class ShowNotificationService extends Service {
int id;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
id = intent.getIntExtra("_id", -1);
return START_STICKY;
}
@Override
public void onCreate() {
switch(id) {
case AlarmStarterService.REQUEST_CODE_DAILY:
showDailyNotification();
break;
case larmStarterService.REQUEST_CODE_MONTHLY:
showMonthlyNotification();
break;
}
stopSelf();
}
}