Skip to content

Instantly share code, notes, and snippets.

@sharish
Created July 26, 2015 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharish/5329d4aef27e315d9a3d to your computer and use it in GitHub Desktop.
Save sharish/5329d4aef27e315d9a3d to your computer and use it in GitHub Desktop.
package com.cooltechworks.ondownsample;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by sharish on 7/24/15.
*/
public abstract class OnDownListener implements View.OnTouchListener {
public static final long ONE_SECOND = 1 * 1000;
private static final long MAX_DOWN_COUNT = 10;
private boolean isPressed;
private Thread mCheckThread;
private long mDownCount = 0;
private long mDownTimeDuration = 0;
public abstract void onDown(View v, long callingCount);
/**
* Gets the maximum down event count beyond which no more event will be passed.
* @return
*/
public long getMaxDownCount() {
return MAX_DOWN_COUNT;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
setPressed(true);
startLooping(v);
return true;
case MotionEvent.ACTION_UP:
setPressed(false);
clear();
break;
}
return false;
}
private void startLooping(final View v) {
mCheckThread = new Thread() {
public void run() {
while (isPressed && getMaxDownCount() >= mDownCount) {
try {
v.post(new Runnable() {
@Override
public void run() {
mDownTimeDuration += getInterEventTimeout();
onDown(v, mDownCount);
mDownCount++;
}
});
long nextTimeout = getInterEventTimeout();
if(nextTimeout <= 0) {
throw new RuntimeException("Timeout should always be > 0, the received inter event timeout was "+nextTimeout );
}
sleep(nextTimeout);
}catch (InterruptedException e) {
// when released, interrupted exception will be thrown as the release call will interrupts this thread.
// so print only if the thread was interrupted not by release call
if( isPressed) {
e.printStackTrace();
}
}
}
}
};
mCheckThread.start();
}
public void setPressed(boolean pressed) {
synchronized (this) {
this.isPressed = pressed;
}
}
public void clear() {
setPressed(false);
mDownCount = 0;
if(mCheckThread != null) {
mCheckThread.interrupt();
}
}
/**
* Gets the timeout duration between events.
* This will be useful if you want events happening various time duration.
*/
public long getInterEventTimeout() {
return ONE_SECOND;
}
/**
* Gets the downtime duration.
* @return
*/
public final long getDownTimeDuration() {
return this.mDownTimeDuration;
}
/**
* Gets the down count.
* @return
*/
public final long getDownCount() {
return mDownCount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment