【问题标题】:Stop Repeating Alarm in OnReceive which is set in Activity在 Activity 中设置的 OnReceive 中停止重复警报
【发布时间】:2012-08-23 04:01:58
【问题描述】:

我想停止或取消活动中设置的 BroadcastReceiver 的 onReceive 方法中的重复警报。应该在哪里调用cancel()方法,如何在BroadCastReceiver的OnReceive方法中获取alarmManager的实例。

下面是代码sn-p

public void onCreate(Bundle savedInstanceState) {

setContentView(R.layout.main);

Intent intent1 = new Intent(this, MyBroadcastReceiver.class);       

PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);  

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE)

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                + (i * 1000), 60*1000, pendingIntent);

}

公共类 MyBroadcastReceiver 扩展 BroadcastReceiver {

静态整数ID;

@Override

public void onReceive(Context context, Intent intent) {

// Vibrate the mobile phone

Vibrator vibrator = (Vibrator) context
                .getSystemService(Context.VIBRATOR_SERVICE);

vibrator.vibrate(2000);

id=id+1;

NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

Notification notification = new Notification(R.drawable.ic_launcher,
                "A new notification", System.currentTimeMillis());

// Hide the notification after its selected

notification.flags |= Notification.FLAG_AUTO_CANCEL;

Intent intent1 = new Intent(context, Repeat.class);

PendingIntent activity = PendingIntent.getActivity(context, id, intent1,
                PendingIntent.FLAG_CANCEL_CURRENT);

notification.setLatestEventInfo(context, "This is the title",
                "Notified", activity);

notification.number += 1;


notificationManager.notify(id, notification);




 String as = Context.ALARM_SERVICE;

    PendingIntent sender = PendingIntent.getBroadcast(context, 1234567, intent, 0);  

    AlarmManager amg = (AlarmManager) context.getSystemService(as);

    amg.cancel(sender); 


}

}  

【问题讨论】:

  • 如何将警报对象传递给接收器以取消警报
  • 很久过去了,你找到解决办法了吗?

标签: android notifications broadcastreceiver alarmmanager


【解决方案1】:

当您想取消闹钟时,可以使用以下代码。 (我没有对此进行测试,但我做了类似的事情来取消 NotificationService)

    String as = Context.ALARM_SERVICE;
    AlarmManager amg = (AlarmManager) this.getSystemService(as);
    PendingIntent myIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent1, 0);
    amg.cancel(myIntent); 

【讨论】:

  • 我按照你说的做了更改,但无法停止警报,你可以查看代码以供参考。
  • 您需要从警报中传递 PendingIntent 而不是从通知中传递 PendingIntent。
  • 但是活动中存在待处理的警报 Intent 我如何在 OnReceive 中获取它
  • 检查我编辑的答案。您必须使 PendingIntent 成为可以在整个 Activity 中访问的变量
  • James onReceive 是 BroadCastReceiver 中的方法,不在同一个 Activity 类中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多