如何停止Alarm Manager?

时间:2013-01-13 18:10:19

标签: android alarmmanager

我已经创建了启动闹钟,如下所示

 public class MyScheduleReceiver extends BroadcastReceiver {

   // Restart service every 30 seconds
private static final long REPEAT_TIME = 1000 * 5;

@Override
public void onReceive(Context context, Intent intent) {
  AlarmManager service = (AlarmManager) context
    .getSystemService(Context.ALARM_SERVICE);
 Intent i = new Intent(context, MyStartServiceReceiver.class);
 PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
    PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 5);
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
    cal.getTimeInMillis(), REPEAT_TIME, pending);

我把这个用来停止闹钟,我从主要活动中调用它。显示我认为没问题......工作重复但没有停止!!!

      public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setup);

    sendBroadcast(new Intent(this,MyScheduleReceiver.class));

}

public void StopRepeat(View view) {

    sendBroadcast(new Intent(this,MyStopReceiver.class));   

}

 public class MyStartServiceReceiver extends BroadcastReceiver {


 public void onReceive(Context context, Intent intent) {

  Toast.makeText(context, "Repeat service!.",
           Toast.LENGTH_LONG).show();
    }

  public class MyStopReceiver extends BroadcastReceiver {

  // Restart service every 30 seconds
  private static final long REPEAT_TIME = 1000 * 5;

  @Override
  public void onReceive(Context context, Intent intent) {
    AlarmManager service = (AlarmManager) context
        .getSystemService(Context.ALARM_SERVICE);
    Intent istop = new Intent(context, MyStartServiceReceiver.class);
    PendingIntent pending = PendingIntent.getBroadcast(context, 0, istop,
        PendingIntent.FLAG_CANCEL_CURRENT);
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 5);

      service.cancel(pending);

但服务并未停止。可能是什么问题?谢谢。

1 个答案:

答案 0 :(得分:0)

最简单的选择是重启设备。 (如果您创建了BOOT_COMPLETED侦听器,则暂时将其删除。)

您还可以通过将用于创建闹钟的PendingIntent传递给AlarmManager#cancel()来取消闹钟。您已编写代码来执行此操作,但是您是否在android:onClick="StopRepeat"中有一个带有XML属性setup.xml的按钮?你点击了吗?


<强>解决方案
我们最终发现你的Manifest文件中有一个错误,所以MyStopServiceReceiver从未被调用过......