From fc14abc35c8f0439aca7406d429f95cc185e1a87 Mon Sep 17 00:00:00 2001 From: Dimitris Papavasiliou Date: Tue, 11 Dec 2018 19:58:22 +0200 Subject: [PATCH] Properly handle keep-alive alarms for multiple pipes. --- .../api/util/RealtimeSleepTimer.java | 31 ++++++++++++++----- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/android/src/main/java/org/whispersystems/signalservice/api/util/RealtimeSleepTimer.java b/android/src/main/java/org/whispersystems/signalservice/api/util/RealtimeSleepTimer.java index 6b93aaa86e..c1c7e1bc90 100644 --- a/android/src/main/java/org/whispersystems/signalservice/api/util/RealtimeSleepTimer.java +++ b/android/src/main/java/org/whispersystems/signalservice/api/util/RealtimeSleepTimer.java @@ -24,6 +24,7 @@ public class RealtimeSleepTimer implements SleepTimer { private final AlarmReceiver alarmReceiver; private final Context context; + private boolean armed; public RealtimeSleepTimer(Context context) { this.context = context; @@ -32,16 +33,30 @@ public RealtimeSleepTimer(Context context) { @Override public void sleep(long millis) throws InterruptedException { - context.registerReceiver(alarmReceiver, - new IntentFilter(AlarmReceiver.WAKE_UP_THREAD_ACTION)); - - alarmReceiver.setAlarm(millis); + boolean arm; synchronized (this) { - wait(millis); + if (!armed) { + armed = true; + arm = true; + } else { + arm = false; + } } - context.unregisterReceiver(alarmReceiver); + if (arm) { + context.registerReceiver(alarmReceiver, + new IntentFilter(AlarmReceiver.WAKE_UP_THREAD_ACTION)); + + alarmReceiver.setAlarm(millis); + synchronized (this) { + wait(millis); + } + } else { + synchronized (this) { + wait(); + } + } } private class AlarmReceiver extends BroadcastReceiver { @@ -74,9 +89,11 @@ public void onReceive(Context context, Intent intent) { Log.w(TAG, "Waking up."); synchronized (RealtimeSleepTimer.this) { + RealtimeSleepTimer.this.context.unregisterReceiver(this); + + RealtimeSleepTimer.this.armed = false; RealtimeSleepTimer.this.notifyAll(); } } } } -