Search code examples
javablackberrytouchscreen

Detect touch screen in Blackberry?


I am working on a Blackberry application which includes Zoom pinch functionality, but this functionality works in touch screen devices. My app will work on curve type of devices too.

Please let me know if "I can detect programmatically if the device is touch screen or not" so I can make my application flexible for both types.


Solution

  • If you only need to support OS 4.7+ devices, then you don't need to use the preprocessor. You can programmatically test for the touchscreen with this:

    boolean isTouch = TouchScreen.isSupported();
    

    What Rupak suggested in his answer may not be enough (just adding touch handling code, which will be ignored for non-touch devices). In your case, if you want to support a zoom feature, you may need to actively detect a non-touch device (with the code above), and choose to add a new zoom ButtonField, which is not even shown on touch devices that do support the pinch gesture. If you don't do this, then either non-touch devices won't be able to zoom, or touch devices will have their screens cluttered with an unnecessary button.

    But, the TouchScreen API is only for 4.7+. If you need to run the same code on older OS versions, too, this other method can be used:

    boolean isTouch = (new Canvas(){protected void paint(Graphics graphics){}}).hasPointerEvents();
    

    My apps mostly still do support 4.5+, which can't even compile touch handling code. So, I normally rely on this kind of preprocessor macro to selectively compile different code. First, at the top of the file

    //#preprocess
    

    Then, anywhere inside the file:

    //#ifndef TOUCH_SCREEN
    /*
    //#endif
    
    // code only for touch devices:
    import net.rim.device.api.ui.TouchEvent;
    
    //#ifndef TOUCH_SCREEN
    */
    //#endif
    

    And then for builds that I will produce for deployment to touchscreen devices, I add the TOUCH_SCREEN preprocessor flag. If you don't want to worry about uploading different app bundles for touch vs. non-touch devices, just programmatically detect touch screens with the Java code (isTouch) and use the preprocessor just to remove code that won't compile on pre-4.7 OS versions.

    Note: this somewhat confusing "double negative" preprocessor logic is not a mistake. It's like that to accommodate the slightly different way preprocessors in BlackBerry-enabled IDEs (e.g. JDE, Eclipse, Netbeans) handle preprocessing. Unfortunately, preprocessing is not a standardized J2ME feature, so it's implementation is a little flaky.