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

fixing RealtimeSleepTimer to work in concurrent threads #70

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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