Detecting Mobile Devices Using Java

Updated November 2009

Thanks to the magical powers of the Internet, a kind fan of the PHP scripts for detecting mobile devices ported the code to Java. So for those folks using Java, here is a fantastic new option. And of course -- it's free!

For more detailed information about the caveats of attempting to detect mobile devices based on User Agent strings, please see our article on PHP scripting. There are also some useful links to commercial and open source projects for detecting mobile devices in that article.

Quick apologies: I'm not as versed in Java as JavaScript and PHP, so any errors introduced in the code are mine. Satish, the gentleman who ported the PHP code to Java, did a great job! Since he sent the code to me, I've made a few modifications which are commented in the source code. Please accept my apologies in advance for any errors. And if you find any, please let me know!

 

Summary

As with PHP and JavaScript code, the basic concept is to do the following:

  1. Instantiate the class in a JSP page. (Some people may wish to do this in a Struts Action class.)
  2. Detect whether the current web site visitor is using a mobile device;
  3. If yes, redirect to a mobile-optimized page. (Or similar type of custom action for mobile devices.)

 

Introducing the "UAgentInfo" Class

The Java class called "com.handinteractive.mobile.UAgentInfo" encapsulates all of the logic for detecting mobile devices. This class is easy to use and its API is highly modularized so that you can detect broad classes of devices (such as smartphones or WAP/WMP-capable devices) and specific platforms (such as the iPhone/iPod Touch, Symbian S60 or BlackBerry).

Here is a sample block of the code so you can see how it is organized:


//**************************
// The UAgentInfo class encapsulates information about
//   a browser's connection to your web site. 
//   The object's detection methods return booleans: true or false.
public class UAgentInfo
{
   //Stores some info about the browser and device.
   private String userAgent;

   //Stores info about what content formats the browser can display.
   private String httpAccept; 

   // A long list of strings which provide clues 
   //   about devices and capabilities.
   public static final String deviceIphone = "iphone";

   // [ SNIP! Other variables snipped out ] 


   //**************************
   //The constructor. Initializes several default variables.
   public UAgentInfo(String userAgent, String httpAccept) {
        if (userAgent != null) {
            this.userAgent = userAgent.toLowerCase();
        }
        if (httpAccept != null) {
            this.httpAccept = httpAccept.toLowerCase();
        }
    }

   //**************************
   //Returns the contents of the User Agent value, in lower case.
   public String getUserAgent()
   { 
       return userAgent;
   }

   //**************************
   // Detects if the current device is an iPhone.
   public boolean detectIphone()
   {
        //The iPod touch says it's an iPhone! So let's disambiguate.
        if (userAgent.indexOf(deviceIphone) != -1 && !detectIpod()) {
            return true;
        }
        return false;
   }

   // [ SNIP! Other functions snipped out ] 

}

 

Using the "UAgentInfo" Class

First, instantiate the UAgentInfo object, then call one of its functions. The device detection functions return booleans: true or false. It's as simple as that! Here's an example:


//1. Instantiate the object to do our testing with.
<%@page import="com.handinteractive.mobile.UAgentInfo"%>

<%
    //2. Initialize the browser info variables
    String userAgent = request.getHeader("User-Agent");
    String httpAccept = request.getHeader("Accept");

    //3. Create the UAgentInfo object
    UAgentInfo detector = new UAgentInfo(userAgent, httpAccept);

    //4. Detect whether the visitor is using a mobile device.
    //   For example, if it's an iPhone, redirect them to the  
    //   iPhone-optimized version of your web site.
    if (detector.detectIphoneOrIpod()) {
        response.sendRedirect("http://www.mycompany.com/iphone");
    } else {
        response.sendRedirect("http://www.mycompany.com/default");
    }
%>


Let's look at some specific features of the Java API.

 

Detect iPhone & iPod Touch

Use the following code to detect whether the device viewing the page is an iPhone and/or iPod Touch. And don't forget: iPod Touches are devices, too!

Why detect this browser? Mobile Safari is based on WebKit and can render most desktop-targeted web content very well (generally excluding heavy AJAX pages). Don't send users to barebones WAP/WML pages! Instead, give iPhone users regular desktop pages, iPhone-optimized content or nicely formatted mobile-optimized content.


/**
 * Detects if the current device is an iPhone or iPod Touch.
 * In most cases, you'll want to use this function.
 */
public boolean detectIphoneOrIpod()

/**
 * Detects if the current device is an iPhone.
 */
public boolean detectIphone()

/**
 * Detects if the current device is an iPod Touch.
 */
public boolean detectIpod()

 

Detect Symbian S60 Smartphones

The most popular smartphone platform in the world is Symbian S60. Used primarily by Nokia and a few other manufacturers, S60 features an extremely capable browser.

Why detect this browser? Users with S60 phones as a group are the largest consumers of the mobile web. Similar to the iPhone, the S60 Open Source Browser is based on WebKit and can render most desktop-targeted web content very well (generally excluding heavy AJAX pages). Don't send users to barebones WAP/WML pages! Instead, give S60 users regular desktop pages or nicely formatted mobile-optimized content.


/**
 * Detects if the current browser is the S60 Open Source Browser.
 */
public boolean detectS60OssBrowser()

/**
 * Detects if the current device is any Symbian OS-based device,
 *   including older S60, Series 70, Series 80, Series 90, and UIQ, 
 *   or other browsers running on these devices.
 */
public boolean detectSymbianOS()

 

Detect Android Devices

Besides the iPhone, the only other mobile device in recent times to receive as much attention, both from geeky fanboys and the general public, has been the T-Mobile G1, often called the "Google Phone." The G1 is powered by a new mobile phone operating system called Android, created by Google. Android is a smartphone-class OS with an advanced browser similar to the iPhone's in capabilities.

We added new methods to the Java code to detect for Android phones. The first detects simply whether the device is running the Android OS. The second detects whether the browser is based on WebKit (like Mobile Safari). The second method is useful as new browser apps are released for Android.

Why detect this browser? The native Android browser is extremely capable and also based on WebKit, which underlies the iPhone's Mobile Safari & the S60 browser. Generally, if you have web content optimized for the iPhone, also make this content available for Android devices. Additional manufacturers are releasing loads of new Android devices starting in mid-2009.


/**
 * Detects if the current device is an Android OS-based device.
 */
public boolean detectAndroid()

/**
 * Detects if the current device is an Android OS-based device and
 * the browser is based on WebKit.
 */
public boolean detectAndroidWebKit()

 

Detect Windows Mobile Devices

Devices running Windows Mobile are fairly popular in the U.S., especially among business users. This code detects both the non-touch screen (Standard/Smartphone) and touch screen (Professional/PocketPC) types of devices.

Why detect this browser? Pocket Internet Explorer and Opera for Windows Mobile are moderately capable mobile browsers. Don't send users to barebones WAP/WML pages! Instead, give these users either modest desktop pages (avoid AJAX and complicated CSS) or nicely formatted mobile-optimized content. (The latter is probably the better choice.)


/**
 * Detects if the current browser is a Windows Mobile device.
 */
public boolean detectWindowsMobile()

 

Detect BlackBerry Devices

The most popular smartphone platform in the United States. (Still beats the iPhone in sales!) Unfortunately, the BlackBerry browser isn't great.

Why detect this browser? Although the browser isn't as capable as the WebKit ones noted above, it can display nicely (but minimally!)-formatted mobile-optimized content. At least when the browser is set to HTML mode! Otherwise, in WML-only mode, it should be sent the barebones WAP/WML pages.


/**
 * Detects if the current browser is on a BlackBerry of some sort.
 */
public boolean detectBlackBerry() {

 

Detect PalmOS Devices

Last but not least in the smartphone category are the old PalmOS devices. These devices are still fairly popular in the U.S., if less so abroad, and there is a large installed base of PalmOS devices. We'll update this section when Palm releases the Pre (expected by mid-2009).

Why detect this browser? As the device which practically invented the smartphone category, PalmOS devices ship with a browser and a good number of users have data plans. Unfortunately, I don't have a PalmOS device in my device library yet, so I can't make any content format recommendations. (Anyone want to give me a U.S. market unlocked GSM Centro or Pre?)


/**
 * Detects if the current browser is on a PalmOS device.
 */
public boolean detectPalmOS()

 

Additional API Details

Now that we've seen the general pattern for how to use our Java UAgentInfo object, let's see a few more types of devices it can detect. In the interest of space, we won't show the code for each. (But you can download it below!)

  • Detect any smartphone-class device: detectSmartphone()
  • Detect any browser based on WebKit: detectWebkit()
  • Quick check to detect any mobile device. Ought to detect most modern mass market phones as well as smartphones: detectMobileQuick()
  • Longer, more thorough check to see if this is a mobile device. Ought to include the Nokia Internet Tablet and game consoles: detectMobileLong()
  • This device's browser supports WAP/WML content: detectWapWml()
  • This device supports Java MIDP: detectMidpCapable()
  • This device is BREW-powered: detectBrewDevice()
  • This is a Danger Hiptop: detectDangerHiptop()
  • This is a Nokia Internet Tablet (770, N800, or N810): detectMaemoTablet()
  • This is a Sony Mylo: detectSonyMylo()
  • This is an Archos media player/tablet: detectArchos()
  • This is a game console (e.g., Xbox, Wii, Nintendo DS, PSP): detectGameConsole()

 

Enjoy the fun at home!

Download the Java code from our new Google Code page!

The most important caveat is that you should thoroughly test the code for yourself based on your own needs and expectations -- and always using your high priority target devices!

If you find this code useful, please consider donating so we can purchase additional devices on our testing wishlist!


About the Contributor

Our gratitude to Satish K. Nookala, who wrote the initial port of the PHP code to Java. Unfortunately, Satish doesn't have a web site where you can learn more about his great talents, but here's a brief bio in his own words:

"I am a Java programmer and systems analyst working for an Indian software company (right now working at a client location in USA). I have been coding in Java for the last 7 years or so. Also did coding in PERL, PHP, and Visual Basic. I love UNIX and whenever I find some time, I try to explore Linux. :-)"

 

License Info & Costs

We have moved this code library to a Google Code hosting project and changed the license to an Apache License 2.0, which better fits a free, open source project like this. We've also rechristened this project "MobileESP." For more info, please visit the new MobileESP site: www.mobileESP.org


MobileESP Project

Learn more about the new MobileESP project!

We've spun off our mobile device detection code into a FREE open source project called MobileESP! Learn more about it on the new project web site.

Please Donate

If you like and use this code, please consider donating. Any amount is appreciated!

(Please donate -- help us purchase more devices on our testing wishlist!)

About Us

Hand Interactive offers user experience, usability, and business strategy expertise. We're passionate about crafting engaging experiences for mobile, desktop, and web users.

 
Contact us for more information.