Skip to content
This repository has been archived by the owner on Feb 12, 2022. It is now read-only.

Commit

Permalink
Properly handle keep-alive alarms for multiple pipes.
Browse files Browse the repository at this point in the history
  • Loading branch information
Dimitris Papavasiliou committed Dec 11, 2018
1 parent 7d0c3d0 commit 7e5d83a
Showing 1 changed file with 24 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {
Expand Down Expand Up @@ -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();
}
}
}
}

0 comments on commit 7e5d83a

Please sign in to comment.