Domanda

I'm working on an app where I create events and set alarm for the events. I need to know how to cancel alarm. I'm having trouble with it. Anyone can help me please, thanks.

UPDATE
Posted the code, see the code below. AlarmClass.java

Button buttonCancel = (Button) findViewById(R.id.btnCancel);
        buttonCancel.setOnClickListener(new Button.OnClickListener()
        {

            @Override
            public void onClick(View arg0)
            {
                Intent i = new Intent(AlarmClass.this, AlarmReceiver.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(AlarmClass.this, 1, i, 0);



                AlarmManager aManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                aManager.cancel(pendingIntent);

                Toast.makeText(getApplicationContext(), "Alarm has been cancelled", Toast.LENGTH_SHORT).show();
            }


        });
È stato utile?

Soluzione

You can simply cancel an Alarm By cancel() method of AlarmManager.

AlarmManager am; 
.
.
.
am.cancel ( PendingIntent operation ); 

for e.g.

Intent intent = new Intent(this, AlarmReceive.class);
PendingIntent sender = PendingIntent.getBroadcast(this,0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

alarmManager.cancel(sender);

You need to pass the PendingIntent's object into cancel() method.

Altri suggerimenti

To stop a service you can use stopSelf();

One thing to note, which is kind of silly, is that the AlarmManager will actually send the PendingIntent upon calling cancel(). Why it does this, I have no idea. Not sure if you're noticing this, but I am. To fix this I called cancel() on the PendingIntent itself:

   myntent = new Intent(SetActivity.this,AlarmActivity.class);
   pendingIntent = PendingIntent.getActivity(CellManage_AddShowActivity.this,
             id, myntent,PendingIntent.FLAG_UPDATE_CURRENT);
   pendingIntent.cancel();
   alarmanager.cancel(pendingIntent);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top