首页 > 解决方案 > Intent.getSerializableExtra(obj)在设置Alarm时在BroadcastReceiver的onReceive中返回null

问题描述

我想启动一个警报并将一个对象传递给将由触发警报的 BroadcastReceiver 子类接收的意图,但无论我传递给 Intent 什么,它都不会被保存并且收到的 Intent 将为空

这是我的代码:

(设置闹钟):

        private void startAlarm() {
           Girafe girafe = new Girafe("holly");
           int hash = 1
           // set the date of the alarm to be in one minute
           Calendar c = Calendar.getInstance();
           c.add(Calendar.MINUTE, 1); 

           // Create the alarm
           AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
           Intent intent = new Intent(this, AlertReceiver.class);

           // I pass here the object I want to be received on alarm fired
           intent.putExtra("myObject", girafe);
           intent.putExtra("myStr", "hello");
           PendingIntent pendingIntent = PendingIntent.getBroadcast(this, hash, intent, 0);
           alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);

        }

(接收和发出警报):

    public void onReceive(Context context, Intent intent) {

       String myStr = intent.getStringExtra("myStr") // I receive something null here
       Girage g = (Girafe) intent.getSerializableExtra("myObject"); // same here

    }

这里的问题在哪里?

PS:我知道这个问题已经在 7 个月前在这里提出了Intent 在 MyAlarm 类的 onReceive 中为 null,即使我在发送意图时坐在 putExtra但没有人解决它。

标签: javaandroidandroid-intentbroadcastreceiver

解决方案


这行不通。如果您传递自定义对象(即:Android 不知道的对象),AlarmManager则无法反序列化该对象并被忽略。这就是为什么触发警报时您永远不会在“附加”中看到对象的原因。

为了解决这个问题,您可以将对象序列化为byte数组或 aString并将其放入“附加”中。AlarmManager了解byte数组和Strings,因此当警报触发时,您应该在“附加”中看到序列化对象。然后您将需要反序列化byte数组或String自己重新创建对象。

另一个潜在的问题是你这样做:

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, hash, intent, 0);

此调用并不总是创建一个新的PendingIntent. 它可能会返回一个现有的 PendingIntent,其中没有你的“额外”。为确保不会发生这种情况,您应该这样做:

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, hash, intent, PendingIntent.FLAG_UPDATE_CURRENT);

添加FLAG_UPDATE_CURRENT将确保您的“附加”被复制到 中PendingIntent,即使正在返回现有的。


推荐阅读