取消PendingIntent(Broadcast,AlarmManager)不起作用

时间:2017-03-08 18:48:38

标签: android alarmmanager broadcast

我试图取消特定活动的广播

我有以下代码来设置AlarmManager

 done.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i=new Intent(getApplicationContext(),NotificationReciever.class);  // go to NotificationReciever
            i.putExtra("id",getIntent().getStringExtra("id"));  //send id that same id own each item in database
            Toast.makeText(getBaseContext(),getIntent().getStringExtra("id"),Toast.LENGTH_SHORT).show();
            PendingIntent pendingIntent=PendingIntent.getBroadcast(getApplicationContext(),(int)id,
                    i,PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(),pendingIntent); //go to  other activity must be changed to proper notificaton
            Reminder.super.onBackPressed();
        }
    });

当我想删除AlarmManager时......

Intent i=new Intent(getApplicationContext(),NotificationReciever.class);
                        PendingIntent pendingIntent=PendingIntent.getBroadcast(getApplicationContext()
                                ,Integer.parseInt(notesData.getID())
                                ,i
                                ,PendingIntent.FLAG_UPDATE_CURRENT);
                        pendingIntent.cancel();
                        AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
                        alarmManager.cancel(pendingIntent);

但它没有取消AlarmManager,问题是什么?

1 个答案:

答案 0 :(得分:1)

看起来你误解了AlarmManager的概念及其工作原理。我建议你阅读Alarm Manager | Working with example

要回答您的问题 - 要删除预定的警报,您需要删除相应的PendingIntent。在创建PendingIntent

时始终记下两件事
  • ID-这是唯一标识符
  • Flag - Flag定义Pending Intent的行为

要从应用程序中的任何位置取消计划的警报,只需使用相同的请求ID和FLAG_NO_CREATE

再次定义PendingIntent
 PendingIntent pendingIntent=PendingIntent.getBroadcast(this,REQUEST_CODE,intent,PendingIntent.FLAG_NO_CREATE);

 if (pendingIntent!=null)
    alarmManager.cancel(pendingIntent);

使用FLAG_NO_CREATE,如果PendingIntent尚不存在,它将返回null。如果它已经存在,则返回对现有PendingIntent的引用。在取消之前使用FLAG_NO_CREATE,您还可以确认警报是否已经安排。