我有一個setRepeating()
報警計劃,如果它在一定的年齡,我想在它的BroadcastReceiver
禁用。我寧願在BroadcastReceiver
內禁用它,所以如果它可能是我的第一選擇。如何判斷Android重複鬧鈴的年齡?
在我Activity
:
// Start our alarm
Intent intent = new Intent(Main.this, Receiver.class);
long firstTime = SystemClock.elapsedRealtime();
firstTime += 2 * 1000; // start in 2 seconds
long interval = 2000; // 2 seconds for testing
intent.putExtra("start", firstTime); // Tell the receiver the creation date (not working)
PendingIntent sender = PendingIntent.getBroadcast(Main.this, 0, intent, 0);
// Schedule the alarm!
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, interval, sender);
在我BroadcastReceiver
:
@Override
public void onReceive(Context context, Intent intent) {
// ... alarm stuff
long now = SystemClock.elapsedRealtime();
Log.i("", "Alarm Running for " + (now - intent.getLongExtra("start", now)));
//getLongExtra() defaults to 'now' because there is no extra 'start'
}
在logcat的我看到這個..
08-19 11:01:04.420: INFO/(1371): Alarm Running for 0
08-19 11:01:06.420: INFO/(1371): Alarm Running for 0
08-19 11:01:08.430: INFO/(1371): Alarm Running for 0
08-19 11:01:10.420: INFO/(1371): Alarm Running for 0
08-19 11:01:12.419: INFO/(1371): Alarm Running for 0
08-19 11:01:14.419: INFO/(1371): Alarm Running for 0
08-19 11:01:16.420: INFO/(1371): Alarm Running for 0
08-19 11:01:18.420: INFO/(1371): Alarm Running for 0
現在,這對我來說意味着意圖不包含我用putExtra()
給予的「開始」額外費用。
如何通過意向演員或其他方法來判斷鬧鈴的年齡?
編輯:我可以通過創建一個static int
找出接收類接收廣播的次數,並在每次執行警報代碼時遞增它,但這不是找到「年齡」的好方法。
更新:在由莫比烏斯提供的答案組合,還必須通過PendingIntent.FLAG_UPDATE_CURRENT
在PendingIntent.getBroadcast()
,就像如下:
PendingIntent sender = PendingIntent.getBroadcast(Main.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
我就可以了,因爲這是僅用於測試目的,其實並不重要,我如何實現它;)我只是問的問題出於好奇,在這個時候,我除了靜態變量之外,沒有必要實現一個解決方案..這通常不是一個可接受的解決方案,因爲「過度殺傷」,而是可行的解決方案+1 – styler1972