0

есть alarmManager

    @SuppressLint("ShortAlarm")
    private void scheduleAlarm(String hh, int id, String title) {
   
        Intent alarmIntent = new Intent(this, AlarmReceiver.class);
        alarmIntent.setAction("com.hardcoding.homework.AlarmReceiver");
        alarmIntent.putExtra("title", title);
        alarmIntent.putExtra("id", id);
        // int interval =1000*60*2;
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Calendar notifyTime = Calendar.getInstance();

        notifyTime.set(Calendar.HOUR_OF_DAY, H);
        notifyTime.set(Calendar.MINUTE, minut);
        //notifyTime.set(Calendar.SECOND, 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setRepeating
                    (AlarmManager.RTC_WAKEUP,
                            notifyTime.getTimeInMillis(), 1000*60, pendingIntent);
        } else
            alarmManager.setInexactRepeating
                    (AlarmManager.RTC_WAKEUP,
                            notifyTime.getTimeInMillis(), 1000*60, pendingIntent);
    }

принимает время id в виде позиции из lisView и title есть AlarmReciver

public class AlarmReceiver extends BroadcastReceiver {
final public static String ONE_TIME = "onetime";

@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onReceive(Context context, Intent intent) {
    // TODO: This method is called when the BroadcastReceiver is receiving
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
    //Acquire the lock
    wl.acquire();

    //You can do the processing here update the widget/remote views.
    Bundle extras = intent.getExtras();
    StringBuilder msgStr = new StringBuilder();
    //assert extras != null;
    //  String titles= extras.getString("title");
    //  int id = extras.getInt("id",1);
    Intent intents = new Intent(context, DetailsActivity.class);
    String titles = intent.getStringExtra("title");
    int cancelId = intent.getIntExtra("cancelId",-1);
    int id =intent.getIntExtra("id",1);
    Log.d("reciver", "title resiver" + titles);
    Log.d("reciver", "cancelId Reciver" + cancelId);
    Log.d("reciver", "id resiver" + id);

    //Release the lock
    sendNotification(context, "заполните отчет", titles, id,cancelId);
    wl.release();
}

через интент отдаю ему id title и запускаю уведомалнеи методом sendNotification уведомления приходят все как надо в зависимости от нажатых пунктов из лист вью пробую остановить методом CancelAlarm()

    public void CancelAlarm(int id){
    Log.d("debug","cancel alarm ");
    Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
    alarmIntent.putExtra("cancelId", id);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            this, id, alarmIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    alarmManager.cancel(pendingIntent);

}

как остановить конкретное уведомление ? перерыл весь интернет не чего не нашел все уведомления как приходили так и приходят =( заранее благодарен =)

1 ответ 1

2

Для отмены нужно сформировать такой же Intent, с каким было установлено.
Должно быть полное совпадение интент-фильтра (action, data, mime-type, class и category), exstras не имеет значения. Так же важен параметр requestCode в PendingIntent.getXXX()
Соответственно, у вас в методе отмены не хватает строки:

alarmIntent.setAction("com.hardcoding.homework.AlarmReceiver");

И должен совпадать параметр id с тем что был при установке аларма

1
  • да спасибо ) проблема была именно в этом ) alarmIntent.setAction("com.hardcoding.homework.AlarmReceiver");
    – dimasta68
    15 апр 2021 в 7:13

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.