简体   繁体   中英

Set Alarm to Repeat only 3 Times

I am using the AlarmManager.setRepeating (int type, long triggerAtMillis, long intervalMillis, PendingIntent operation) Method in order to set a repeating Alarm. Meanwhile, I would like to set the Alarm to repeat only 3 times, and not indefinitely as this Method does. How could I achieve this?

Create a new variable in SharedPreferences termed alarmCount which we'll increment in AlarmReceiver class (in onReceive() method).

SharedPreferences sharedPreferences = getSharedPreferences("TIMER", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("alarmCount", 1);
        editor.commit();

We set the alarm using the following code -

private void setAlarm() {
    int alarmId = 0;
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra("alarmId", alarmId);
    PendingIntent alarmIntent;
    alarmIntent = PendingIntent.getBroadcast(context,
            alarmId, intent,
            0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
            1000 * 60 * 1, alarmIntent);
    Log.e("alarm", "set");
}

According the documentation -

Depending on your app, you may want to include the ability to cancel the alarm. To cancel an alarm, call cancel() on the Alarm Manager, passing in the PendingIntent you no longer want to fire.

Thus, you'll then code the AlarmReceiver to cancel the alarm once count reaches 3.

Then, in our AlarmReceiver, we match the alarmId we used earlier, and cancel the same alarm once count reaches 3.

@Override
    public void onReceive(Context context, Intent intent) {
        int alarmId = intent.getExtras().getInt("alarmId");
        PendingIntent alarmIntent;
        alarmIntent = PendingIntent.getBroadcast(context, alarmId, new Intent(context, AlarmReceiver.class),
                0);
        //increment alarmCount
        SharedPreferences sharedPreferences = context.getSharedPreferences("TIMER", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        int alarmCount = sharedPreferences.getInt("alarmCount", 1);
        editor.putInt("alarmCount", alarmCount+1);
        editor.commit();
        Log.e("alarmCount ", alarmCount+"");

        if(alarmCount == 3) {
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
            alarmManager.cancel(alarmIntent);
        Log.e("Alarm","Cancelled");
        }

As you can see from the sceenshot , the alarm did not repeat after being cancelled (no logs).

Let me know if this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM