/*
Swisscom Safe Connect
Copyright (C) 2014 Swisscom
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.swisscom.safeconnect.activity;
import android.os.Handler;
import java.util.Vector;
/**
* Created by vadim on 30.10.14.
* Runnable Handler class that supports buffering up of Runnables when the
* activity is paused i.e. in the background.
*/
public class PauseHandler extends Handler {
/**
* Runnable Queue Buffer
*/
final Vector<Runnable> runnableQueueBuffer = new Vector<Runnable>();
/**
* Flag indicating the pause state
*/
private boolean paused;
/**
* Resume the handler
*/
final public void resume() {
paused = false;
while (runnableQueueBuffer.size() > 0) {
final Runnable run = runnableQueueBuffer.elementAt(0);
runnableQueueBuffer.removeElementAt(0);
post(run);
}
}
/**
* Pause the handler
*/
final public void pause() {
paused = true;
}
/**
* call this method to execute the runnable if the activity is not paused
* or store the runnable to be executed as soon as the activity is resumed
* @param r runnable
*/
public void postRunnable(Runnable r) {
if (paused) {
runnableQueueBuffer.add(r);
} else {
post(r);
}
}
public void postDelayedRunnable(Runnable r, long delayMs, boolean oneInstance) {
if (paused) {
runnableQueueBuffer.add(r);
} else {
if (oneInstance) {
removeCallbacks(r);
}
postDelayed(r, delayMs);
}
}
}