android - 除了第一个之外,所有 Intent 都收到了不正确的额外内容

标签 android android-intent broadcastreceiver

我有一个小应用程序,可以用来为 future 的事件设置提醒。该应用程序使用 AlarmManager 来设置提醒用户的时间。当闹钟响起时,BroadcastReceiver 会对此进行注册,然后启动一项服务,通过 toast 和状态栏中的通知来通知用户。

为了在通知和 toast 中显示正确的信息,一些额外的信息随 Intent 一起传递。第一次注册提醒时,BroadcastReceiver 接收并传递给服务的信息是正确的。但是对于每个后续提醒(即 BroadcastReceiver 收到的每个新 Intent ),即使发送的信息不同,此信息也保持不变。

例如,如果字符串“foo”作为第一个 Intent 的额外内容,则“foo”会被 BroadcastReceiver 正确提取。如果在第二个 Intent 中将“bar”作为额外内容放置,“foo”仍由 BroadcastReceiver 提取。

这是注册警报并传递 Intent 的代码(主 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);
}

list 中的 Intent 过滤器:

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

我已经坚持了一段时间,所以非常感谢帮助!

最佳答案

尝试添加 FLAG_UPDATE_CURRENT当您通过 getBroadcast() 创建它时添加到您的 PendingIntent

关于android - 除了第一个之外,所有 Intent 都收到了不正确的额外内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1517016/

相关文章:

android - 需要将数据从一个 Activity 传递到另一个引用数据库

android - 多通知处理

android - BroadcastReceiver 多久监听一次 Intents

java - Android:检测用户是否停止使用他的手机一段时间

java - Android系统应用

java - 随机生成方程和答案

Android IntentFilter 性能

即使在一次注册后,Android BroadcastReceiver onReceive() 在 android 5.1.1 上调用了两次

java - 无法在intellij创建android项目

android - 在 4.1.2 中为单个来电广播两次