我正在尝试通过在接收器中使用处理程序来使用setExact()
重复我的警报,但是当警报第二次触发时(由处理程序触发的警报),会出现此错误。
java.lang.NullPointerException: Attempt to invoke virtual method "java.lang.Object android.content.Context.getSystemService(java.lang.String)" on a null object reference
我在sendNotification()
中致电我的onCreate()
public void sendNotification() {
Calendar cal = Calendar.getInstance();
Calendar newDay = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 23);// 10 am
cal.set(Calendar.MINUTE, 22);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
if (cal.getTimeInMillis() < newDay.getTimeInMillis())
cal.add(Calendar.DATE, 1);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, 0 , intent , 0 ) ;
if(alarmManager != null ) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),pendingIntent1);
}else {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY , pendingIntent1);
}
}
}
这是我的通知接收者
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// my logic
(new Handler()).postDelayed(new Runnable() {
@Override
public void run() {
MainActivity mainActivity = new MainActivity();
mainActivity.sendNotification();
}
},60 * 1000); // ONE MINUTE
}
}
我该如何解决这个问题?