java - 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但没有人解决它。
解决方案
这行不通。如果您传递自定义对象(即:Android 不知道的对象),AlarmManager
则无法反序列化该对象并被忽略。这就是为什么触发警报时您永远不会在“附加”中看到对象的原因。
为了解决这个问题,您可以将对象序列化为byte
数组或 aString
并将其放入“附加”中。AlarmManager
了解byte
数组和String
s,因此当警报触发时,您应该在“附加”中看到序列化对象。然后您将需要反序列化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
,即使正在返回现有的。
推荐阅读
- python - 使用 python 解释性能结果的好方法是什么?
- hyperledger-fabric - 部署链码时内存不足
- influxdb - 如何在通量查询中的正则表达式条件内转义正斜杠“/”
- javascript - 在浏览器中为节拍器准确计时声音
- python - 如何在 Networkx 和 matplotlib 中标记多图的边缘?
- popover - 如何给 ngbpopover 边框
- python - 蟒蛇协助
- python - Python 3 比较列表变量
- typescript - 如何在 GraphQL 的解析器中获取输入类型的数组
- reactjs - Jest中带有参数的测试函数作为匿名函数