In my application I'm trying to have particles emanating from possibly multiple touch locations.
I have a class for storing a point and an associated timer:
private static class Touch
{
public Timer timer = new Timer();
public vec position = new vec();
}
Inside the onTouchEvent, in case of MotionEvent.ACTION_POINTER_DOWN I instance a new Touch:
Touch t = new Touch();
t.position = new vec(event.getX(id), event.getY(id));
t.timer.scheduleAtFixedRate(new TimeredTouchTask(t.position, id), 0, SHOOTING_INTERVAL);
and store it inside a map, using the touch id as key.
If MotionEvent.ACTION_POINTER_UP gets fired I remove the touch by calling cancel() on the timer and by removing it from the map.
Finally, if the event is of type MotionEvent.ACTION_MOVE I simply iterate all the Touch instances inside the map and update the vector coordinates.
This works but sometimes timers won't get removed correctly, sometimes they are kept alive doing nothing and sometimes they keep on actually shooting particles even if I stopped touching the screen.
How could I make this code more robust so it will always behave correctly?
edit1: the code of ACTION_POINTER_UP
I call this method
private void removeTouch(int id)
{
Touch t = _touch.get(id);
if(t != null)
{
if(t.timer != null)
{
t.timer.cancel();
t.timer = null;
}
t = null;
_touch.remove(id);
}
}
edit2: the full listing LINK
By examining some logs I found out that for example: Touch finger #1 Touch finger #2 Touch finger #3 Release finger #3 Release finger #2 Release finger #1
is ok but doing:
Touch finger #1 Touch finger #2 Touch finger #3 Release finger #1 Release finger #2 Release finger #3
leaks the last timer. I think I'm definitively messing with id's and indexes.
Judging from your use of getX(id), etc, I'm guessing id is the pointer index, not the pointer id. Pointer indexes aren't guaranteed to stay persistent across touch events, so you may not be finding the same timer when you use it for later events.
You should use the pointer id to track which is which. getPointerId() will give you that for each index.
If you haven't read it already, I highly recommend reading Making Sense of Multitouch on the Android blog.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With