I have an app with multiple alarms at the same time. Those alarms must restart once completed. My problem actually is how to retrieve the requestCode of my alarm once it is received, or at least passing some parameters with the alarm and retrieve them once alarm completed. Is there a way to do it?
here is my BroadcastReceiver
public class Alarm extends BroadcastReceiver {
private static final int SECS = 1000;
private static final int MINS = 60000;
private static final int HOURS = 3600000;
private static final int DAYS = 86400000;
@Override
public void onReceive(Context ctx, Intent intent){
PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
//qui metto il codice
//todo codice
Toast.makeText(ctx, "Allarme!", Toast.LENGTH_SHORT).show();
wl.release();
}
public void setAlarm(Context ctx, int sec, int min, int hours, int days, int requestCode){
AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(ctx, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(ctx, requestCode, i, 0);
int tempoInMilli = 0;
tempoInMilli += (SECS * sec);
tempoInMilli += (MINS * min);
tempoInMilli += (HOURS * hours);
tempoInMilli += (DAYS * days);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), tempoInMilli, pi);
}
public void cancelAlarm(Context context, int requestCode)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, requestCode, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
And this is my service
public class AlarmService extends Service {
Alarm alarm = new Alarm();
public void onCreate(){
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Bundle extras = intent.getExtras();
int sec = extras.getInt("secondi");
int min = extras.getInt("minuti");
int hour = extras.getInt("ore");
int days = extras.getInt("giorni");
int requestCode = extras.getInt("requestCode");
alarm.setAlarm(this, sec, min, hour, days, requestCode);
return START_STICKY;
}
@Override
public void onDestroy(){
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
}
Now, my alarms are all saved with an id and the request code (plus a description and some other infos) with SQLite in the local db. The only goal i'm missing(i think) is to retrieve the requestCode or an identifier from the alarm when it is completed.
It's the first time I work with alarms so i might be missing something, so any tip will be appreciated!