BroadcastReceiver中的Serializable Extras

时间:2018-04-09 19:41:07

标签: android android-intent serialization broadcastreceiver android-pendingintent

我正在开发具有闹钟功能的Android应用程序。

到目前为止一直很好,我使用this tutorial作为警报管理器,但我在使用PendingIntents时遇到了一些问题。

一切正常,直到我尝试在我的Intent上发送额外的Object,当涉及到另一方时,Object(巫婆实现Serializable类)为null。

这是我的代码:

Intent intent = new Intent(context, AlarmMedicBroadcastReceiver.class);
intent.setAction(AlarmeMedicamentoBroadcastReceiver.ACTION_ALARM);
intent.putExtra("alarm", dto); // <- My Object that extends Serializable

/* Setting 10 seconds just to test*/
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
long tempo = cal.getTimeInMillis();

PendingIntent alarmIntent = PendingIntent.getBroadcast(context, dto.getId(), intent, 0);
AlarmManager alarme = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    alarme.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, tempo, alarmIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    alarme.setExact(AlarmManager.RTC_WAKEUP, tempo, alarmIntent);
} else {
    alarme.set(AlarmManager.RTC, tempo, alarmIntent);
}

在我的Receiver课程中:

@Override
public void onReceive(Context context, Intent intent) {
    if(ACTION_ALARM.equals(intent.getAction())){

        AlarmeMedicamentoDTO alarm = (AlarmeMedicamentoDTO) intent.getExtras().getSerializable("alarm");
        /*for this moment, alarm is null*/

        /*Other Stuff*/

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);

        notificationBuilder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setTicker("Company name")
                //     .setPriority(Notification.PRIORITY_MAX)
                .setContentTitle("Alarme de Medicamento")
                .setContentText("Hora de tomar seu medicamento: " + alarm.getNomeMedicamento()) //<- Null Pointer Exception
                .setContentIntent(pendingIntent)
                .setContentInfo("Info");

        notificationManager.notify(1, notificationBuilder.build());

    }
}

提前致谢

2 个答案:

答案 0 :(得分:2)

您无法再将自定义对象添加为&#34; extras&#34;传递给Intent的{​​{1}}。在更新版本的Android中,AlarmManager尝试解压缩&#34;额外内容&#34;并且它不知道如何解压缩您的自定义对象,因此这些将从&#34; extras&#34;中删除。 您需要将自定义对象序列化为字节数组并将其放在&#34; extras&#34;中,或将自定义对象存储在其他位置(文件,SQLite DB,静态成员变量等)

答案 1 :(得分:0)

您必须将自定义对象包装在 Bundle 中:

包裹在捆绑中:

Bundle bundle = new Bundle();
bundle.putSerializable("myObject", theObject);
intent.putExtra("myBundle", bundle); // <- Object that extends Serializable

从意图中获取(在接收器中):

Bundle bundle = intent.getBundleExtra("myBundle");
YourCustomClass theObject = (YourCustomClass) bundle.getSerializable("myObject"); 

YourCustomClass 可以是任何实现 Serializable

的类