我的作业计划器应用程序中有一个启动接收器,用于重新设置所有为提醒用户他们的作业到期而创建的警报。每次我的手机启动时,我都会收到“作业计划器已停止”,我想不通出为什么。而且我不能使用 LogCat,因为它在启动时没有连接(?)。
这是我在引导接收器中的代码。
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// RE-SET ALL ALARMS FROM THE DATABASE WHEN PHONE IS TURNED ON
HomeworkDatabase db = new HomeworkDatabase(context);
db.open();
ArrayList<HomeworkItem> hwks = db.getHomeworks();
db.close();
int reminders = 0;
for (int e = 0; e < hwks.size(); e++) {
HomeworkItem current = hwks.get(e);
{
Calendar c = Calendar.getInstance();
c.set(current.year, current.month, current.day, 0, 0);
long alarmTime = c.getTimeInMillis();
Intent i = new Intent(HomeworkList.getAppContext(),
RegularAlarm.class);
i.putExtra("title", current.title);
i.putExtra("id", current.id);
PendingIntent pi = PendingIntent.getBroadcast(
HomeworkList.getAppContext(), (int) current.id, i, 0);
AlarmManager mAlarm = (AlarmManager) context
.getApplicationContext().getSystemService(
Context.ALARM_SERVICE);
mAlarm.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
reminders++;
}
if (current.oneDayReminder == true) {
Calendar c = Calendar.getInstance();
c.set(current.year, current.month, current.day, 0, 0);
c.roll(Calendar.DAY_OF_MONTH, -1);
long alarmTime = c.getTimeInMillis();
Intent i = new Intent(HomeworkList.getAppContext(),
OneDayAlarm.class);
i.putExtra("title", current.title);
i.putExtra("id", current.id);
PendingIntent pi = PendingIntent.getBroadcast(
HomeworkList.getAppContext(), (int) current.id, i, 0);
AlarmManager mAlarm = (AlarmManager) context
.getApplicationContext().getSystemService(
Context.ALARM_SERVICE);
mAlarm.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
reminders++;
}
if (current.twoDayReminder == true) {
Calendar c = Calendar.getInstance();
c.set(current.year, current.month, current.day, 0, 0);
c.roll(Calendar.DAY_OF_MONTH, -2);
long alarmTime = c.getTimeInMillis();
Intent i = new Intent(HomeworkList.getAppContext(),
TwoDaysAlarm.class);
i.putExtra("title", current.title);
i.putExtra("id", current.id);
PendingIntent pi = PendingIntent.getBroadcast(
HomeworkList.getAppContext(), (int) current.id, i, 0);
AlarmManager mAlarm = (AlarmManager) context
.getApplicationContext().getSystemService(
Context.ALARM_SERVICE);
mAlarm.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
reminders++;
}
}
Log.d("hwk","BOOT COMPLETE: " + reminders + " alarms created");
Toast.makeText(context, reminders + " alarms created at boot", Toast.LENGTH_LONG);
}
}
抱歉,代码片段很长,但我不知道问题出在哪里。
谢谢
编辑:错误的来源是在创建意图并从 PendingIntent 获取上下文时。
Intent i = new Intent(HomeworkList.getAppContext(), RegularAlarm.class);
此行导致空指针异常。知道为什么吗?