关于intent Extra的Android广播通知NullPointerException

时间:2017-08-04 14:17:09

标签: java android android-intent nullpointerexception android-broadcast

我需要每天8:30在TaskManager中发出有关任务的通知。

以下是我的活动代码:

request.GetRequestContext()

在我的广播接收器中,我有这段代码

public final static String INTENT_LIST_FOR_NOTIFICATION = "tasks for notification";

private void setUserNotifications() {
        long targetTime = targetCalendar.getTimeInMillis();
        long currentTime = targetCalendar.getTimeInMillis();

        Intent intent = new Intent(this, MyScheduledReceiver.class);
        intent.putExtra(INTENT_LIST_FOR_NOTIFICATION, taskArrayList);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        if (currentTime >= targetTime) {
            targetCalendar.add(Calendar.DAY_OF_MONTH, 1);
            targetTime = targetCalendar.getTimeInMillis();
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, targetTime, AlarmManager.INTERVAL_DAY, pendingIntent);
        }
        else {
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, targetTime, AlarmManager.INTERVAL_DAY, pendingIntent);
        }
    }

但我对arrayList有疑问。之后

public class MyScheduledReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent scheduledIntent = new Intent(context, MainActivity.class);
        scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                scheduledIntent, 0);

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        ArrayList<MyTask> arrayList = (ArrayList<MyTask>) intent.getSerializableExtra(MainActivity.INTENT_LIST_FOR_NOTIFICATION);
        for (int i = 0; i < arrayList.size(); i++) {
            Notification notification = new Notification.Builder(context)
                    .setContentIntent(contentIntent)
                    .setContentTitle(arrayList.get(i).getmTaskName()) 
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setTicker("")
                    .setWhen(System.currentTimeMillis()).setAutoCancel(true)
                    .build();

            notificationManager.notify(arrayList.get(i).getTaskId(), notification);
        }

    }
}

它为null并且在字符串

中有NullPointer Exception
ArrayList<MyTask> arrayList = (ArrayList<MyTask>) intent.getSerializableExtra(MainActivity.INTENT_LIST_FOR_NOTIFICATION);

这是例外:

for (int i = 0; i < arrayList.size(); i++) {

注意:它仅适用于API 24和下一个。 Api 23和之前的工作很好。

1 个答案:

答案 0 :(得分:0)

发送

intent.putStringArrayListExtra(MainActivity.INTENT_LIST_FOR_NOTIFICATION,taskArrayList)

接收

intent.getStringArrayListExtra(MainActivity.INTENT_LIST_FOR_NOTIFICATION)