Skip to content

Commit

Permalink
Merge pull request #1 from theBoatman/FixingRealtimeSleepTimer
Browse files Browse the repository at this point in the history
Fixing realtime sleep timer signalapp#70
  • Loading branch information
five-c-d authored Jun 23, 2019
2 parents 0bb7f60 + a4ef3e0 commit d59a09e
Showing 1 changed file with 21 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@
import android.os.SystemClock;
import android.util.Log;

import org.whispersystems.signalservice.api.util.SleepTimer;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.ConcurrentSkipListSet;

/**
* A sleep timer that is based on elapsed realtime, so
Expand All @@ -21,41 +19,50 @@
*/
public class RealtimeSleepTimer implements SleepTimer {
private static final String TAG = RealtimeSleepTimer.class.getSimpleName();
private static ConcurrentSkipListSet<Integer> actionIdList = new ConcurrentSkipListSet<>();

private final AlarmReceiver alarmReceiver;
private final Context context;

public RealtimeSleepTimer(Context context) {
this.context = context;
alarmReceiver = new RealtimeSleepTimer.AlarmReceiver();
}

@Override
public void sleep(long millis) {
context.registerReceiver(alarmReceiver,
new IntentFilter(AlarmReceiver.WAKE_UP_THREAD_ACTION));
final AlarmReceiver alarmReceiver = new RealtimeSleepTimer.AlarmReceiver();
int actionId = 0;
while (!actionIdList.add(actionId)){
actionId++;
}
try {
context.registerReceiver(alarmReceiver,
new IntentFilter(AlarmReceiver.WAKE_UP_THREAD_ACTION + "." + actionId));

final long startTime = System.currentTimeMillis();
alarmReceiver.setAlarm(millis);
final long startTime = System.currentTimeMillis();
alarmReceiver.setAlarm(millis, AlarmReceiver.WAKE_UP_THREAD_ACTION + "." + actionId);

while (System.currentTimeMillis() - startTime < millis) {
while (System.currentTimeMillis() - startTime < millis) {
try {
synchronized (this) {
wait(millis - System.currentTimeMillis() + startTime);
}
} catch (InterruptedException e) {
Log.w(TAG, e);
}
}
context.unregisterReceiver(alarmReceiver);
} catch(Exception e) {
Log.w(TAG, "Exception during sleep ...",e);
}finally {
actionIdList.remove(actionId);
}

context.unregisterReceiver(alarmReceiver);
}

private class AlarmReceiver extends BroadcastReceiver {
private static final String WAKE_UP_THREAD_ACTION = "org.whispersystems.signalservice.api.util.RealtimeSleepTimer.AlarmReceiver.WAKE_UP_THREAD";

private void setAlarm(long millis) {
final Intent intent = new Intent(WAKE_UP_THREAD_ACTION);
private void setAlarm(long millis, String action) {
final Intent intent = new Intent(action);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
final AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

Expand Down

0 comments on commit d59a09e

Please sign in to comment.