所有意图都收到了错误的额外信息,除了第一个意图。

12
我有一个小应用程序,可以用来设置将来事件的提醒。该应用程序使用AlarmManager设置用户应被提醒的时间。当闹钟响起时,BroadcastReceiver会注册并启动一个服务来通过Toast和状态栏中的通知来通知用户。
为了在通知和Toast中显示正确的信息,一些额外的信息通过意图传递。第一次注册提醒时,接收BroadcastReceiver并传递给服务的信息是正确的。但对于每个后续提醒(即BroadcastReceiver接收到的每个新意图),即使发送的信息不同,这些信息仍然保持不变。
例如,如果在第一个意图中将字符串"foo"作为额外信息放置,则BroadcastReceiver正确提取"foo"。如果在第二个意图中添加字符串"bar",则BroadcastReceiver仍将提取"foo"。
以下是注册闹钟并传递意图的代码(主UI类):
Intent intent = new Intent(ACTION_SET_ALARM);
intent.putExtra("desc", desc);
intent.putExtra("time", time);
intent.putExtra("dbId", dbId);
intent.putExtra("millis", millis);
PendingIntent pIntent = PendingIntent.getBroadcast(quickAlert.this, 0, intent, 0);

// Schedule the alarm!
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, millis, pIntent);

BroadcastReceiver类中的onReceive()方法:

@Override
public void onReceive(Context context, Intent intent) {

    Intent i = new Intent(context, AlertService.class);

    String desc = intent.getStringExtra("desc").equals("") ? "": ": " + intent.getStringExtra("desc");
    String time = intent.getStringExtra("time");
    long dbId = intent.getLongExtra("dbId", -1);
    long millis = intent.getLongExtra("millis", -1);

    i.putExtra("desc", desc);
    i.putExtra("time", time);
    i.putExtra("dbId", dbId);
    i.putExtra("millis", millis);
    Log.d(TAG, "AlertReceiver: " + desc + ", " + time + ", " + dbId + ", " + millis);

    Toast.makeText(context, "Reminder: " + desc, Toast.LENGTH_LONG).show();
    context.startService(i);
}

在清单文件中的 intent-filter:

<receiver android:name=".AlertReceiver">
        <intent-filter>
            <action android:name="com.aspartame.quickAlert.ACTION_SET_ALARM" />
        </intent-filter>
    </receiver>

我被这个问题困扰了一段时间,非常感谢你的帮助!

3个回答

28

9
上面的答案是正确的,但它们缺少解释。值得注意的是PendingIntent文档中的这一部分:
“PendingIntent本身只是一个引用,指向由系统维护的描述用于检索它的原始数据的令牌。...如果创建应用程序稍后重新检索相同类型的PendingIntent(相同的操作、相同的Intent动作、数据、类别和组件以及相同的标志),它将接收表示相同令牌的PendingIntent。”
请注意,“额外”数据在PendingIntent标识的概念中特别不包括

哇,当我发现这个的时候,我真的很惊讶。谢谢你的解释!你为我省了很多烦恼。 - Salivan

5

此外,如果您也使用FLAG_UPDATE_CURRENT,那就更好了。 - Sreekanth Karumanaghat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接