-2

can any one help me in creating multiple alarms .If any one has example of this.Please send me because I am new to android.If any one has example in working form on multiple alarm, please send me.

Tom Tom
  • 3,680
  • 5
  • 35
  • 40

1 Answers1

2

Use the below method to create multiple alarms, for each different alarm send a different value in pk field. timeinmilis is the time in milliseconds when the alarm should go off.

public void setAlarm(Context context, int pk, long timeinmilis) {
        AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent alarmIntent = new Intent(context, AlarmReceiver.class);
        alarmIntent.putExtra("alarm", pk);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, pk, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
            manager.setExact(AlarmManager.RTC_WAKEUP, , pendingIntent);
        else
            manager.set(AlarmManager.RTC_WAKEUP, time.getMillis(), pendingIntent);
}

To cancel the alarm just send the integer value in pk that was used to create the alarm.

public void cancelAlarm(Context context, int pk) {
        AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent alarmIntent = new Intent(context, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, pk, alarmIntent, PendingIntent.FLAG_NO_CREATE);
        manager.cancel(pendingIntent);
    }

Create a class extending BroadCastReceiver to receive when the alarm goes off.

public class AlarmReceiver extends BroadcastReceiver {
    private PowerManager.WakeLock wl;

    @Override
    public void onReceive(Context context, Intent intent) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backgroundwakelock");
        wl.acquire();
        //add code to do something when alarm goes off
        wl.release();
    }
}

Note: Added WakeLock so that if running in background, WakeLock would wake up the CPU. It would need the below permission to be added in AndroidManifest.xml

<uses-permission android:name="android.permission.WAKE_LOCK" />
Psypher
  • 10,717
  • 12
  • 59
  • 83