【问题标题】:Trouble sending Bundle with PendingIntent to a Broadcast Receiver, data lost无法将带有 PendingIntent 的 Bundle 发送到广播接收器,数据丢失
【发布时间】:2010-09-16 17:09:54
【问题描述】:

我正在通过使用 AlarmManager 和 BroadcastReceiver 类(名为 AReceiver.java)向我的程序添加一些基本的警报功能。我的问题是我添加到附加到创建 PendingIntent 的 Intent 的捆绑包中的数据似乎丢失了。我可以在 AReceiver 类中访问的唯一捆绑数据是 android.intent.extra.ALARM_COUNT=1。

以下是主活动类中创建 Intent、PendingIntent 和 AlarmManager 的基本代码: [主要活动中的代码 - Notepadv3]

Intent intent = new Intent(Notepadv3.this, AReceiver.class);         
intent.putExtra("teststring","hello, passed string in Extra");               
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, pendingPeriodIntentId, intent, 0);     
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);           
am.set(AlarmManager.RTC_WAKEUP, timeOfNextPeriod.getTimeInMillis(), alarmIntent);

[BroadcastReceiver 中的代码 - AReceiver]

public void onReceive(Context con, Intent arg1) {
Bundle extrasBundle = arg1.getExtras();
Log.d("broadcast","contains teststring = " + extrasBundle.containsKey("teststring"));
Log.d("broadcast","is empty? = " + extrasBundle.isEmpty());
Log.d("broadcast","to string = " + extrasBundle.toString());
    }   

调试消息说包含 teststring 为 FALSE,为空为 FALSE,当输出整个包时,我得到 android.intent.extra.ALARM_COUNT=1 值。

任何帮助将不胜感激。

干杯, 汤姆

【问题讨论】:

    标签: android bundle broadcastreceiver


    【解决方案1】:

    你必须改变这一行

    PendingIntent alarmIntent = PendingIntent.getBroadcast(this, pendingPeriodIntentId, intent, 0);
    

    进入这个

    PendingIntent alarmIntent = PendingIntent.getBroadcast(this, pendingPeriodIntentId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    

    否则数据会丢失

    【讨论】:

    • 谢谢!这就是解决方法,我搜索了高低以获取正确的参数。再次感谢。
    • 奇怪,在 android 4.0.3 模拟器上它适用于 0 和 PendingIntent.FLAG_UPDATE_CURRENT
    • 但是...当您执行后者时,它会覆盖任何 现有 附加内容。这意味着如果我们想添加新的附加功能并保留现有的,它就行不通。通常将 0 作为标志传递会导致此工作(例如,如果在 PendingIntent 上调用 send 而不是使用 AlarmManager 调度它)。什么给了?
    • 对于 Android 4.4.2,即使标志设置为 0,我也可以从 Intent 检索额外内容,而在 Android 5 中,即使使用 FLAG_UPDATE_CURRENT,额外内容也会丢失,
    猜你喜欢
    • 2020-12-22
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多