2012-09-03 53 views
2

我正在开发一个应用程序,在其中创建事件并为事件设置警报。我需要知道如何取消警报。我遇到了麻烦。任何人都可以帮助我,谢谢。如何在android中取消闹钟?

UPDATE
发布的代码,请参见下面的代码。 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(); 
      } 


     }); 

回答

1

您可以简单地取消AlarmManager的报警方法cancel()

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

例如,

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

alarmManager.cancel(sender); 

您需要将PendingIntent的对象传递给cancel()方法。

+0

我已经在我的应用程序中编码过,但没有工作。我会发布我的代码,看看我的代码中是否有任何错误或缺失。 – Preeyah

+0

我刚刚发布的代码,请看看。谢谢 – Preeyah

+0

什么?你已经开始报警,并在下次取消它?那么报警的目的是什么? – Lucifer

0

要停止服务,您可以使用stopSelf();

0

有一点要注意,这是一种愚蠢的,就是AlarmManager实际上会在调用取消()发送的PendingIntent。为什么它这样做,我不知道。不知道你是否注意到这一点,但我是。为了解决这个问题,我在PendingIntent本身调用了cancel():

myntent = new Intent(SetActivity.this,AlarmActivity.class); 
    pendingIntent = PendingIntent.getActivity(CellManage_AddShowActivity.this, 
      id, myntent,PendingIntent.FLAG_UPDATE_CURRENT); 
    pendingIntent.cancel(); 
    alarmanager.cancel(pendingIntent);