AlarmManager永远不会为BroadcastReceiver返回事件,如何调试?

时间:2011-12-17 20:04:14

标签: android broadcastreceiver alarmmanager

下面的代码不会抛出任何错误,也不会起作用。当我调试addInvoiceReminder()方法时,它正在正确设置时间,并且AlarmManager设置为在先前设置的时间关闭。有人能看到我的缺陷吗?我不确定为什么BroadcastReceiver的onRecieve事件永远不会触发。

//---adds an invoice reminder when the user successfully adds a sales or expense invoice---
 public void addInvoiceReminder () {
    //---gets a Calendar object with current time---
     Calendar cal = Calendar.getInstance();
     //---sets the calendar object to the reminder dialog date---
     //cal.set(reminder_year, reminder_month, reminder_day);
     cal.add(Calendar.SECOND, 30);

     Intent intent = new Intent(this, DueInvoiceAlarmReceiver.class);
     intent.putExtra("reminder", "Invoice Number: 999999 is due!");         
     PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);

     //---gets the alarm manager service set for the calendar time which is the reminder time---
     AlarmManager alarm_manager = (AlarmManager) getSystemService(ALARM_SERVICE);
     alarm_manager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
 }

 //---Receives the event fired when the reminder date for an invoice is passed---
 public class DueInvoiceAlarmReceiver extends BroadcastReceiver {        
     @Override
     public void onReceive(Context context, Intent intent) {
       try {
         Bundle bundle = intent.getExtras();
         String message = bundle.getString("reminder");
         Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
         Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
         e.printStackTrace();        
        }
     }       
 }

2 个答案:

答案 0 :(得分:1)

确保在清单中声明广播接收器。

答案 1 :(得分:0)

尝试Calendar cal = cal .getInstance(); cal.setTimeInMillis(System.currentTimeMillis());

因为你试图在磨坊中获得时间,但从未设置它。