重复我的警报将引发NullPointerException

时间:2019-03-18 06:24:18

标签: java android nullpointerexception

我正在尝试通过在接收器中使用处理程序来使用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);
        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
    }
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我假设MainActivity是Android Studio创建的类,您应该从不创建活动类的实例。 Android Studio自动分配活动,上下文,片段和必要的东西。如有必要,请在MainActivity中定义一个静态getInstance()方法,该方法将返回上下文并使用该方法。