我目前正在创建一个简单的计划管理器,它使用警报管理器在出现问题或启动时触发广播接收器。我可以成功地将广播接收器设置为onReceive但是附加到intent的所有附加内容都将为null。触发器类只需获取接下来的内容并为其设置警报。我已经把头撞到墙上两天了,现在我觉得我现在对这个问题太熟悉了。
public class Trigger {
private Context mConext;
private Schedule schedule;
private StringTime stringTime;
public Trigger(Schedule schedule, Context activity){
this.schedule = schedule;
this.mConext = activity;
this.stringTime = new StringTime();
}
public void setNext(){
//returns a time in string format ie "11:00"
String nextScan = schedule.getNextScanTime();
String triggerType = "Scan";
if (nextScan == null){
nextScan = "00:00";
triggerType = "Schedule";
}
Log.d("Intended trigger", nextScan);
Log.d("Trigger type", triggerType);
Intent alarmIntent = new Intent(mConext, TriggerReceiver.class);
alarmIntent.putExtra("Trigger", triggerType);
alarmIntent.putExtra("Lecture", schedule.getTodaysLectures().get(0));
PendingIntent pendingIntent = PendingIntent.getBroadcast(mConext, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
setAlarm(getTriggerTimeAsCalendar(nextScan), pendingIntent);
}
//returns a calendar set with the nextScan time
private Calendar getTriggerTimeAsCalendar(String nextScan){
// get a Calendar object with current time
Calendar cal = Calendar.getInstance();
Log.d("Current Time", cal.getTime().toString());
int nextScanHour = stringTime.getHourFromString(nextScan);
int nextScanMinute = stringTime.getMinuteFromString(nextScan);
cal.set(Calendar.HOUR_OF_DAY, nextScanHour);
cal.set(Calendar.MINUTE, nextScanMinute);
cal.set(Calendar.SECOND, 0);
if (nextScan.equals("00:00")){
cal.add(Calendar.DAY_OF_MONTH, 1);
}
return cal;
}
private void setAlarm(Calendar cal, PendingIntent pendingIntent){
AlarmManager manager = (AlarmManager) mConext.getSystemService(Context.ALARM_SERVICE);//get instance of alarm manager
manager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);//set alarm manager with entered timer by converting into milliseconds
Log.d("Next Trigger", cal.getTime().toString());
}
public class TriggerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Calendar cal = Calendar.getInstance();
Log.d("Triggered", cal.getTime().toString());
Bundle extras = intent.getExtras();
String message = extras.getString("Trigger");
//Always Null?
System.out.println(message);
}