How to : Multitouch event in Android SDK
 
 

The guys at Google recently informed us that the next version of the Android SDK will not support multitouch yet.

This is sad as I can think of a thousand of applications for this little multitouch thingy.

But fear not my friends, I have found a workaround to feature part of the multitouch functionnality. I needed it for my future game ArmaBoing, so I decided to hunt into the SDK, and guess what multitouch was not that well hidden :D

So here you go :

In your onTouchEvent method, the parameter sent to you is a MotionEvent Type.

When they implemented that object it was supposed to be multitouch capable. For reason I cannot understand (Apple fear anyone ?), they decided not to release it.

And they're of way of hidding it was a good and simple one : Set the second touch members x2 and y2 as private.

Damn how to get around that : easy enough !!

They forgot to remove it from the MotionEvent.toString() that allows to have a human readable form of the object, and guess what.....x2 and y2 are right there ready to be parsed and used !!

event.ToString() returns :

MotionEvent{43559a18 action=0 x=71.69278 y=340.1937 x2=101.85449 y2=349.0169 pressure=0.3254902 size=0.06666667}

So here my multitouch function that gets an event and send you back the position of the multitouch as an Android SDK Point :

//Function that hacks into the motionevent.tostring to get
//the x2 and y2 coordinate work around the lack of multitouch
private Point getMultiTouchSecondPosition(MotionEvent event) {

    String eventString=event.toString();
    Point point2=new Point(0,0);

    //Get the x2 coordinate
    Pattern pattern = Pattern.compile("x2=([0-9.]+)");

    Matcher matcher = pattern.matcher(eventString);

    if (matcher.find()) {
        point2.x=Math.round(Float.parseFloat(matcher.group(1)));
    }


    //Get the y2 coordinate
    pattern = Pattern.compile("y2=([0-9.]+)");

    matcher = pattern.matcher(eventString);

    if (matcher.find()) {
        point2.y=Math.round(Float.parseFloat(matcher.group(1)));
    }

    return(point2);
}

Everything is not perfect though :

- x2 and y2 are not set back to 0 when a multitouch end or when single touch are triggered, they keep their last values until another multi touch is triggered.

- This is a hack, so you should probably not rely on it if you program real applications. The Android team could read this post and decide to completely lock the multi touch capacity of our phones.

So here you have it, i did not do much more experiment as it works for my purpose. Have fun.

 

Androidement vôtre !!

Yahel Bouaziz.