下面的代码不会引发任何错误,也不会起作用。当我调试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();
        }
     }
 }

最佳答案

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

10-07 16:03
查看更多