【问题标题】:Intent.getSerializableExtra(obj) returns null in onReceive of BroadcastReceiver when setting up AlarmIntent.getSerializableExtra(obj)在设置Alarm时在BroadcastReceiver的onReceive中返回null
【发布时间】:2019-11-11 12:34:05
【问题描述】:

我想启动一个警报并将一个对象传递给将由触发警报的 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 getting null in onReceive in MyAlarm class even though I sat putExtra while sending intent 但没有人解决它。

【问题讨论】:

  • 什么是hash
  • it will not be save and the Intent received will be null 不。意图不为空。但intent.getStringExtra("myStr") 将返回 null。如果不是那么清楚。
  • 尝试不放长颈鹿。
  • 我将 hash 替换为 1(简单请求代码)。事实上,intent.getStringExtra("myStr") 返回 null
  • 那么请更改您的主题和我们帖子中的文字。

标签: java android android-intent broadcastreceiver


【解决方案1】:

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

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

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2017-02-12
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多