Android, How to cancel an alarm? alarmManager.canc

2020-07-18 06:31发布

I have an application where you can create 5 alarms where to be created are displayed in a ListView, and assume that when an element of listView the played alarm but should remove the item from the listview but the alarm is removed to reach the scheduled time always sounds. I have reviewed muchísmos tutorials and guides on how to remove the alarms but none helped me. To delete what I do is save the ID of each alarm in a sqlite database and when I give the alarm eliminiar what I do is I bring the id of the alarm that want to eliminate and give it to PendingIntent.getBroadcast to remove the alarm you want but it does not happen. Someone could check my code and tell me if any error'm falling in such so that the alarm is not eliminated. Thank You

This method I use to create alarms

public void agregarAlarma(Calendar targetCal){
    final int _id = ((int)System.currentTimeMillis()/1000);
    Random generator = new Random();
    DbHelper helper = new DbHelper(this);
    SQLiteDatabase bd = helper.getWritableDatabase();

    int id_nuevo = (_id + generator.nextInt());
    if(alarma.getSelectedItem().toString().equals("Desayuno")){
        comida = alarma.getSelectedItem().toString() + " " + targetCal.getTime().toString();
        descripcion = "del desayuno";
    }else if(alarma.getSelectedItem().toString().equals("Primera Merienda")){
        comida = alarma.getSelectedItem().toString() + " " + targetCal.getTime().toString();
        descripcion = "de la primera merienda";
    }else if(alarma.getSelectedItem().toString().equals("Almuerzo")){
        comida = alarma.getSelectedItem().toString() + " " + targetCal.getTime().toString();
        descripcion = "del almuerzo";
    }else if(alarma.getSelectedItem().toString().equals("Segunda Merienda")){
        comida = alarma.getSelectedItem().toString() + " " + targetCal.getTime().toString();
        descripcion = "de la segunda merienda";
    } else if(alarma.getSelectedItem().toString().equals("Cena")){
        comida = alarma.getSelectedItem().toString() + " " + targetCal.getTime().toString();
        descripcion = "de la cena";

    }

    Intent intent;
    PendingIntent pendingIntent;
    AlarmManager alarmManager;

    if(tablaVacia()>= 5){
         Toast.makeText(this,"Esta lista solo permite 5 alarmas, elimine alguna para crear otra nueva",Toast.LENGTH_SHORT).show();
    }else{
         intent  = new Intent(Recordatorios2.this, AlarmReceiver.class);
        intent.putExtra("Comida",comida);
         pendingIntent = PendingIntent.getBroadcast(Recordatorios2.this, id_nuevo ,intent, PendingIntent.FLAG_ONE_SHOT);
         alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
        descripcionTotal = "Alarma  " + descripcion  + " creada "+ targetCal.getTime().toString();
        Toast.makeText(this,descripcionTotal,Toast.LENGTH_SHORT).show();
        ContentValues valores = new ContentValues();
        valores.put("Descripcion",comida);
        valores.put("Identificador",id_nuevo);
        bd.insert("Alarmas",null,valores);
        llenarListaAlarmas1();
    }



}

This filled the listView

    public void llenarListaAlarmas1(){
    listaAlarmas = (ListView)findViewById(R.id.listAlarma);
    lista.clear();
    DbHelper helper = new DbHelper(this);
    SQLiteDatabase bd = helper.getWritableDatabase();

    Cursor c = bd.rawQuery(CONSULTA_ALARMAS,null);

    if(c.moveToFirst()){
        do{
            alarmaDatos = new AlarmaDatos(c.getString(0),null);
            lista.add(alarmaDatos);
        }while (c.moveToNext());
    }
    final ArrayAdapter<AlarmaDatos> adapter1 = new ArrayAdapter<AlarmaDatos>(getApplicationContext(),android.R.layout.simple_list_item_1,lista);
    adapter1.notifyDataSetChanged();
    listaAlarmas.setAdapter(adapter1);
    adapter1.notifyDataSetChanged();

    listaAlarmas.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView adapterView, View view, int position, long id) {

            switch (position){


                case 0:
                    seleccion = adapter1.getItem(position).toString();
                    eliminarAlarma();
                    adapter1.notifyDataSetChanged();
                    lista.remove(position);

                    break;
                case 1:
                    seleccion = adapter1.getItem(position).toString();
                    eliminarAlarma();
                    adapter1.notifyDataSetChanged();
                    lista.remove(position);
                    break;

                case 2:
                    seleccion = adapter1.getItem(position).toString();
                    eliminarAlarma();
                    adapter1.notifyDataSetChanged();
                    lista.remove(position);
                    break;
                case 3:
                    seleccion = adapter1.getItem(position).toString();
                    eliminarAlarma();
                    adapter1.notifyDataSetChanged();
                    lista.remove(position);
                    break;
                case 4:
                    seleccion = adapter1.getItem(position).toString();
                    eliminarAlarma();
                    adapter1.notifyDataSetChanged();
                    lista.remove(position);
                    break;
            }


        }
    });

    }

AND THIS IS THE ONE THAT USE TO ELIMINATE THE ALARMS

                public void eliminarAlarma(){
                DbHelper helper = new DbHelper(getApplicationContext());
                SQLiteDatabase bd = helper.getWritableDatabase();
                int identificador =0;
                String CONSULTA_ID = "SELECT Identificador FROM Alarmas WHERE Alarmas.Descripcion = '" + seleccion + "';" ;
                Cursor cursor = bd.rawQuery(CONSULTA_ID,null);
                if(cursor.moveToFirst()){
                    do{
                        alarmaDatos = new AlarmaDatos(cursor.getString(0),null);
                        identificador = Integer.parseInt(alarmaDatos.toString());

                    }while (cursor.moveToNext());
                }
                Intent intent  = new Intent(getBaseContext(), AlarmReceiver.class);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), identificador ,intent,0);
                AlarmManager alarmManager = (AlarmManager)getSystemService(getApplicationContext().ALARM_SERVICE);
                alarmManager.cancel(pendingIntent);
                pendingIntent.cancel();
                borrar(identificador);
                Toast.makeText(getApplicationContext(),"Alarma eliminada",Toast.LENGTH_SHORT).show();

            }

Can someone please lend me a hand with this, because the truth is not because it eliminates the alarm if everything looks good.

TKS

2条回答
再贱就再见
2楼-- · 2020-07-18 06:57

Create

preference_saved_value =  DatabaseConstants.NOTIFICATION_ID
sender = PendingIntent.getBroadcast(this,preference_saved_value, intent,
PendingIntent.FLAG_UPDATE_CURRENT)

CANCEL

sender = PendingIntent.getBroadcast(this, 
preference_saved_value, intent,PendingIntent.FLAG_UPDATE_CURRENT);  
sender.cancel()
查看更多
叼着烟拽天下
3楼-- · 2020-07-18 07:06

No need to call pendingIntent.cancel();, so take out that line.

Also, the PendingIntent should be constructed exactly as it was when you scheduled the AlarmManager.

From the documentation, two Intents are considered equal if:

their action, data, type, class, and categories are the same. This does not compare any extra data included in the intents.

So it would be something like this:

 Intent intent  = new Intent(getBaseContext(), AlarmReceiver.class);
 PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), identificador , intent, PendingIntent.FLAG_NO_CREATE);
 AlarmManager alarmManager = (AlarmManager)getSystemService(getApplicationContext().ALARM_SERVICE);
 alarmManager.cancel(pendingIntent);
查看更多
登录 后发表回答