我通过使用AlarmManager和BroadcastReceiver类(名为AReceiver.java)为我的程序添加了一些基本的报警功能。我的问题是我添加到附加到创建PendingIntent的Intent的包的数据似乎丢失了。我可以在AReceiver类中访问的唯一bundle数据是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值。
非常感谢任何帮助。
干杯, 汤姆
答案 0 :(得分:34)
你必须改变这一行
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, pendingPeriodIntentId, intent, 0);
进入这个
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, pendingPeriodIntentId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
否则数据丢失