отменить повторяющийся будильник в определенное время

Я хочу отменить 2 повторяющихся будильника в определенное время, но в настоящее время приложение решает вызвать отмену, как только вы создадите будильники. Например, если вы установите время окончания повторения в 13:18, то повторяющийся будильник должен повторяться до этого времени.

Вот часть кода, с которым я играл:

Toast.makeText(this, "Alarm Scheduled for " + midnight, Toast.LENGTH_LONG).show();


    AlarmManager Databackon = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

      Databackon.set(AlarmManager.RTC_WAKEUP,midnight, stoprepeat(V));
    // Databackon.set(AlarmManager.RTC_WAKEUP,midnight, PendingIntent.getBroadcast(this,4,  intent, PendingIntent.FLAG_UPDATE_CURRENT));



     Toast.makeText(this, "THIS " + midnight, Toast.LENGTH_LONG).show();


    /*  
      Button button1=(Button)findViewById(R.id.startupdates);
      button1.setVisibility(View.INVISIBLE);
      Button button2=(Button)findViewById(R.id.stopbutton);
      button2.setVisibility(View.VISIBLE);
    */
}

public PendingIntent stoprepeat(View V)
{
    Intent intent = new Intent(UpdatesActivity.this,AlarmReciever.class);
    PendingIntent pendingIntent =
            PendingIntent.getBroadcast(this,1,  intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.cancel(pendingIntent);

    Intent intent2 = new Intent(UpdatesActivity.this,DataOff.class);
    PendingIntent pendingIntent2 =
            PendingIntent.getBroadcast(this,2, intent2,PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am2 = (AlarmManager) getSystemService(ALARM_SERVICE);
    am2.cancel(pendingIntent2);

        Toast.makeText(this, "Repeating Alarm stopped", Toast.LENGTH_LONG).show();

          Button button1=(Button)findViewById(R.id.startupdates);
          button1.setVisibility(View.VISIBLE);
          Button button2=(Button)findViewById(R.id.stopbutton);
          button2.setVisibility(View.INVISIBLE);

        return pendingIntent;
}

person user3668879    schedule 23.05.2014    source источник


Ответы (1)


Ваш код не имеет смысла. Вы должны помнить о трех основных вещах:

  1. Все тревоги привязаны к конкретному приложению.
  2. Функциональность сигналов тревоги основана на ожидающих намерениях.
  3. Аннулирование может быть выполнено при совпадении с конкретным Intent.

Учитывая это, вы можете реализовать следующее решение.

Создайте базовую тревогу как обычно:

Intent myIntent = new Intent(this, Target.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);

Создайте еще один будильник, который будет отвечать за отмену и поставьте ему pendingIntent из 1-го будильника:

Intent cancellationIntent = new Intent(this, CancelAlarmBroadcastReceiver.class);
cancellationIntent.putExtra("key", pendingIntent);
PendingIntent cancellationPendingIntent = PendingIntent.getBroadcast(this, 0, cancellationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, time, cancellationPendingIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Где CancelAlarmBroadcastReceiver это следующее:

public class CancelAlarmBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        PendingIntent pendingIntent = intent.getParcelableExtra("key");
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.cancel(pendingIntent);
    }
}

Не проверял, но думаю должно работать.

person nikis    schedule 23.05.2014
comment
ЭПИКА Вы не представляете, насколько это помогло БОЛЬШОЕ ВАМ СПАСИБО - person user3668879; 29.05.2014
comment
отличный ответ. очень помог. :) - person Yeahia2508; 22.02.2016