在我的活動中,我管理用戶提供的食物列表,並根據它們何時到期設置警報。然而由於某種原因,傳遞給onRecieve的意圖不是我認爲應該的意圖。Android getExtras/Intent與預期的不同
例如,用戶輸入有效日期爲5/8的漿果和有效期爲6/4的漿果,然後點擊保存數據。對於每個項目調用此方法。每次我調用此方法時,我都會使用putExtra保存到期日期。
public void setOneTimeAlarm(int daysAfterSet) {
//declare intent using class that will handle alarm
Intent intent = new Intent(this, FoodExpAlarm.class);
//retrieve pending intent for broadcast, flag one shot means will only set once
intent.putExtra("expDate", expDate);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
//params: specify to use system clock use RTC_WAKEUP to wakeup phone for notification,
//time to wait, intent
alarmMan.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + (daysAfterSet * AlarmManager.INTERVAL_DAY), pendingIntent);
}
這將導致一個報警漿果設置,因爲它們是接近到期,和黃油沒有報警(這是一個月遠離到期)。然後調用foodExpAlarm類一次,並正確顯示漿果的通知。然而,問題來自於下一批食物何時進入。接下來,用戶輸入培根到期5/8和香蕉5/15。現在,setOneTimeAlarm被再次調用兩次(每次調用一次),foodExpAlarm再次被調用,用於培根。
但是,在foodExpAlarm中,傳入的附加信息來自黃油而不是培根。 這對我來說沒有意義,因爲foodExpAlarm應該在時間過去之後調用,並且應該使用與預定時間相對應的待定意圖調用foodExpAlarm。然而,似乎並不是這樣,意圖(或者至少是附加)似乎只對應於所有食物添加的順序。
執行摘要:
- 添加漿果5/8
- 添加黃油6/4
- 保存
- 正確顯示漿果通知
- 放入臘肉5/8
- 添加香蕉5/15
- 保存
- 錯誤地顯示黃油
我的問題是,爲什麼我得到黃油和培根的意圖/額外?我對意圖的理解是錯誤的嗎?我怎樣才能解決這個問題?
foodExpAlarm:
public void onReceive(Context context, Intent intent) {
Bundle exp = intent.getExtras(); //This gets the extras from butter, not bacon like I want
Object temp = exp.get("expDate");
Enter_Foods.expDate = new DateTime(temp);
intent.getExtras();
int id = (int) (Enter_Foods.expDate).getMillis();
....
notificationMan = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
//i think this gets pending intent from the alarm that called this method
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context,MainActivity.class), Intent.FLAG_ACTIVITY_NEW_TASK);
//creates notification object/icon, and set text to flow across top bar
Notification notif = new Notification(R.drawable.ic_launcher,
"Food expiring soon", System.currentTimeMillis());
//specify what to display when notification is shown
notif.setLatestEventInfo(context, from, message, contentIntent);
//use nofication manager to send message to phone, will update if same id
notificationMan.notify(id, notif);
}
我認爲它與Activity.setIntent()有關。我認爲你必須重寫onNewIntent並更新actitiy以使用新的意圖.. – j2emanue 2013-05-06 00:03:07
這是否會影響傳遞給onRecieve的參數? – farnett 2013-05-06 00:10:21
發佈您用於設置通知的代碼。 – 2013-05-06 11:28:15