Find duration between touch events in android - java

I have set up an onTouchListener which allows the user to click textView2 exactly 10 times, as shown below. My goal is to measure the time between touch 1 and touch 2, and store it as a variable, say time1. However, I'm not quite sure how to do this. One idea I had was setting up a variable, i, that measures the number of times the TouchListener was clicked. I was thinking of potentially measuring the time that i contained a particular value (for example, if i was equal to 1 for 1 second, this means the time between touch 1 and touch 2 was 1 second). However I'm not sure how to implement this, and I'm not even sure if this is the correct method. Does anyone know how to solve this problem?
.java file
public class MainActivity extends Activity {
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView2 = (TextView)findViewById(R.id.textView2);
i=0;
textView2.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
i++;
if (i==10) textView2.setOnTouchListener(null);
}
return false;
}
});
}

In your class
private long pressTime = -1l;
private long releaseTime = 1l;
private long duration = -1l;
Then in your onTouch method
if(event.getAction() == MotionEvent.ACTION_DOWN){
pressTime = System.currentTimeMillis();
if(releaseTime != -1l) duration = pressTime - releaseTime;
}
else if(event.getAction() == MotionEvent.ACTION_UP){
releaseTime = System.currentTimeMillis();
duration = System.currentTimeMillis() - pressTime;
}
Now you have your duration between touch events:
Duration when you press down is the time between the last time you released and the current press (if you have previously pressed down and released the button).
Duration when you release is the time between the last time you pressed down and the current release time.
-Edit-
If you need to know the difference in time of all events you can just do something like
private long lastEvent = -1l;
private long duration = -1l;
Then in onTouch event
if(lastEvent != -1l) duration = System.currentTimeMillis() - lastEvent;
lastEvent = System.currentTimeMillis();
You can also create a list of durations
private List<Long> durations = new ArrayList<Long>();
and in onTouch instead of duration = ... do
durations.add(System.currentTimeMillis() - lastEvent);
This could be useful for checking all durations between all sequential events. For example, if you want to know the time between pressing down, dragging, stopping dragging, starting dragging, and then lifting up you could check your list after you lift up for every time in question instead of having to constantly check a single duration.

You may want to keep a record of events in a List. The objects stored in this list would keep the timestamp of the touch event, and since UI events are dispatched by a single thread and the clock is monothonic, you are guaranteed that event at N + 1 has a later (at most equal) timestamp than event at index N.
I'm not sure about how you clean this list, however. It depends on how and why you read events, which in turn depends on what you want to do with the delay between two subsequent touch.
For example, if you just wanted to display the time since last touch, a simple code like this could be enough:
public class MyActivity {
private int times = 0;
private long lastTimestamp;
private void onTouchEvent(Event evt) {
if (times > 0) {
long delay = evt.getTimestamp() - lastTimestamp;
// do something with the delay
}
lastTimestamp = evt.getTimestamp();
times++;
}
}

Related

Solved - Java ShakeDetector triggers multiple times - How to get last output?

So I wrote an android app for dice rolling, with adjustable dice (D4-100), amounts and bonuses.
It works all fine when I press the roll button, but I also wanted it to react to shaking my phone.
The problem is, when i shake it once, it displays the result, but if i shake for too long, the shown results get visibly overwritten - I don't want the user to just keep on shaking until the result is accepted!.
Is there some way to gather all ShakeEvents and only trigger the last one that occured?
Here's what's inside onCreate related to those ShakeEvents:
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
ShakeDetector shakeDetector = new ShakeDetector(this);
shakeDetector.start(sensorManager);
and here's the "hearShake()" method (from Square, Inc.'s seismic):
#Override
public void hearShake() {
Toast.makeText(this, "Rolling...", Toast.LENGTH_SHORT).show();
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(250,VibrationEffect.DEFAULT_AMPLITUDE));
} else {
v.vibrate(250);
}
rollButton.performClick();
}
Solution:
in rollButton.performClick(); I added long lastShake = System.currentTimeMillis();
The content of hearShake() is wrapped inside if (separateShake()):
public boolean separateShake(){
return ((System.currentTimeMillis() - lastShake) > 3000) ? true : false;
}
Now rollButton.performClick() only gets triggered if there's at least a 3 second delay between the shakes, which is fine for me!
One solution would be to record the time at which the shake is recorded and ignore any additional shakes that occur within, say, the next 3 seconds. That way they'd have to do quite a long shake for it to count as multiple.

Double (chess like) timer

I am thinking about making an android app to support a game of mine, and I can't find info on how to do it. Here is an app explanation:
The app should have two timers (both set for x minutes). When first player starts his turn (by a button click) his time starts running out. when first player makes his move, he should click his time to stop it, and player two starts his turn.
NOW, the problem I can't find a solution for - When player one takes his turn, time that he loses should pass to the other player's timer.
Example: Both players start with a 5 minute timer. If player one takes 30 second for his turn, his time should go down to 04:30, at which time he clicked on his timer. During that time, for each second he lost, the other player gained time on his timer, so at the beginning of his turn, his time is 05:30. The time goes back and forth, and the player whose timer runs out loses the game.
Any idea how to do this?
I am still stuck to the idea on how to make it, so I have no code to share.
Thank you all for your answers, and effort in helping me, if you have a question I haven't covered, I will gladly answer it.
First, you will need to instantiate class of CountDownTimer everytime you click on button.
For reference check here: https://developer.android.com/reference/android/os/CountDownTimer.html
You have two parameters long millisInFuture, long countDownInterval
Before you start, you will need to create two global variables one for first player, and one for second player like this:
long firstPlayerRemainingTime = 5 * 60 * 1000; // start time 5 minutes
long secondPlayerRemainingTime = 5 * 60 * 1000;
long limitedTime = 30 * 1000; // 30 seconds
CountDownTimer mCountDownTimer;
Now we have came to the most important part and that is logic inside onClickListener method
I don't know if there are two buttons or one, but I will go with two buttons:
btnFirstPlayer.setTag(1); // start timer
btnFirstPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btnFirstPlayer.getTag() == 1) {
startTimer();
} else {
stopTimer();
}
});
private void startTimer() {
long startTime = firstPlayerRemainingTime;
btnFirstPlayer.setTag(2); // stop timer
btnFirstPlayer.setText("Stop");
mCountDownTimer = new CountDownTimer(firstPlayerRemainingTime, 1000) {
public void onTick(long millisUntilFinished) {
firstPlayerRemainingTime = millisUntilFinished;
tvPlayerOneTimer.setText("" + firstPlayerRemainingTime / 1000)
// Here you would like to check if 30 seconds has passed
if ((startTime / 1000) - (limitedTime / 1000)
== (firstPlayerRemainingTime / 1000)) {
stopTimer();
}
// Here you would like to increase the time of the second player
secondPlayerRemainingTime = ++1000;
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
}
}
private void stopTimer() {
btnFirstPlayer.setTag(1);
btnFirstPlayer.setText("Start");
mCountDownTimer.cancel();
// I guess here starts second player move
}
The same logic would go for second player. Let me know if this helped you or if I need to explain anything.

Can't set delay in libgdx

I want to remove an index from an array after some time, I want it to fall, then delete it.
private final int gravity = 4;
private long lifeTime=0;
private long delay = 20000L;
public void objGravity() {
while (array.get(array.size - 1).y > 0)
array.get(array.size - 1).y -= gravity;
lifeTime = System.currentTimeMillis();
lifeTime += Gdx.graphics.getDeltaTime();
if (lifeTime > delay) {
array.removeIndex(array.size - 1);
lifeTime = 0;
}
}
The object gets removed from array immediately as if there's no delay whatsoever, so it doesn't appear to be falling down on the screen.
Update
I removed time and so on. I added a counter to count how many objects need to be removed and then I do a loop that removes array.size-1 as long as counter>0.
Not sure if it's the best approach, seems like a hack but I don't want to do threads on old mobile phones. If you have a better idea please share
Don't fire threads inside the render method, it's not safe, can cause thread leaks, a lot of other problems and will be harder to maintain your code, to handle time use a variable adding delta time every time render is called, when this variable is superior a 1.0f means that one second has passed, your code would be something like this:
private float timeSeconds = 0f;
private float period = 1f;
public void render() {
//Execute handleEvent each 1 second
timeSeconds +=Gdx.graphics.getRawDeltaTime();
if(timeSeconds > period){
timeSeconds-=period;
handleEvent();
}
[...]
}
public void handleEvent() {
[...]
}
To keep organized i personally have an array on my main game class that holds all my timed events and process everything on the render cycle.

Mp3 player with timer in java [fast forward]

I'm making fast forward button in my Mp3 player. I wrote already code for this, but have problem how to implement timer to jump 5% forward? I mean when I press button timer should jump 5% forward of total long song. This is my fastForward method.
public void FastForward(){
try {
//songTotalLength = fis.available();
fis.skip((long) ((songTotalLength * 0.05)));
} catch (IOException e) {
e.printStackTrace();
}
}
And here is the button method:
private void jButton3ActionPerformed(ActionEvent e) {
mp3.FastForward();
if(mp3.player.isComplete()){
bar = 100;
}
jProgressBar1.setValue((int)bar);
bar+=5;
}
And this one is for timer:
private void setTime(float t) {
int mili = (int) (t / 1000);
int sec = (mili / 1000) % 60;
int min = (mili / 1000) / 60;
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
end.set(Calendar.MINUTE, 0 + min);
end.set(Calendar.SECOND, 0 + sec);
timer = new javax.swing.Timer(1000, new TimerListener());
percent = (float)100/(min*60+sec);
}
You're already redundantly tracking progress in two variables fis and bar. For the sake of good design, use one of those to determine elapsed time rather than using yet another variable for the same purpose.
but have problem how to implement timer to jump 5% forward?
You seem to have mistaken the purpose of a Timer. According to the Timer class documentation, it:
Fires one or more ActionEvents at specified intervals.
So the timer is not meant to keep track of how much time has elapsed. It will simply invoke the actionPerformed(ActionEvent) method of your TimerListener once per second (every 1000 milliseconds) as you have it configured.
For a more complete answer, please post the code for your TimerListener class.
Notes
It seems that your setTime(float) method is meant to be called repeatedly, so this method should not be initializing the timer variable. Rather initialize the timer once and leave it alone to do its job.
I'm assuming you intended the supplied float parameter t to represent microseconds.
The float data type has only 7 digits of precision. This could be fine since you're interested only in minutes and seconds, otherwise float is only good for up to about four months of seconds before losing accuracy.
It seems like you wanted your button click handler to do this (increment bar sooner):
private void jButton3ActionPerformed(ActionEvent e) {
mp3.FastForward();
bar+=5; // increment bar before checking complete, and before setting progress
if(mp3.player.isComplete()){
bar = 100;
}
jProgressBar1.setValue((int)bar);
}

Using time to determine what instruction is carried out - android

Is there a way to use a timestamp or other feature to determine what action is carried out?
e.g. when a button is clicked 'A' is performed unless the button has been clicked within the last second, otherwise perform B
You can use System.currentTimeMillis(), it returs time in millisecond,
e.g.
long last_click = 0;
// this is you interval time in milliseconds
long myTimeMillis = 1000;
// ... ... ...
// inside button click function
long time = System.currentTimeMillis()
if(time-last_click > myTimeMillis){
do_taskA();
}else{
do_taskB();
}
last_click = time;

Categories