BroadcastReceiver 中的可序列化附加功能

Serializable Extras in BroadcastReceiver

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

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

一切正常,直到我尝试按照我的意图在 Extras 中发送另一个对象,当涉及到另一端时,对象( 实现可序列化 class)为空。

这是我的代码:

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);
}

在我的接收器中 class:

@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());

    }
}

提前致谢

您不能再将自定义对象作为 "extras" 添加到传递给 AlarmManagerIntent。在 Android 的更新版本中,AlarmManager 尝试解压 "extras",但它不知道如何解压您的自定义对象,因此这些从 "extras" 中移除。 您需要将您的自定义对象序列化为字节数组并将其放入 "extras",或者将您的自定义对象存储在其他地方(文件、SQLite 数据库、静态成员变量等)

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

捆绑包装:

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

从意图中获取(在 Receiver 中):

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

YourCustomClass 可以是实现 Serializable

的任何 class