Java Servlets - How do I detect if a user is from a mobile device?

16,394

Solution 1

I'm using the TinyMCE javascript editor

Since you'd like to change the client side behaviour depending on the client, best is to handle this at the client side rather than the server side.

In CSS world, you can hook on the media type to apply styles depending on the media used. Most used media types are screen (usually PCs), handheld (usually mobiles) and print (for the printed page).

You can make use of it to hide the editor by just the following rule in your CSS:

@media handheld {
    #elementIdContainingEditor { display: none; }
}

You can even specify separate stylesheets depending on the media used.

<link rel="stylesheet" href="default.css" media="screen">
<link rel="stylesheet" href="mobile.css" media="handheld">

If the problem is actually more that it doesn't work because JavaScript is disabled on the particular client, then you better have to execute the particular CSS when JS is disabled:

<noscript><style>#elementIdContainingEditor { display: none; }</style></noscript>

Or the other way round, initially hide it and then show it when JS is enabled:

<script>document.getElementById('elementIdContainingEditor').style.display = 'block';</script>

This is more reliable than sniffing the agent in the server side.

Solution 2

I have used the UAgentInfo.java class you can download here (http://code.google.com/p/mobileesp/source/browse/Java/UAgentInfo.java):

private boolean isRequestComingFromAMobileDevice(final HttpServletRequest request){

    // http://www.hand-interactive.com/m/resources/detect-mobile-java.htm
    final String userAgent = request.getHeader("User-Agent");
    final String httpAccept = request.getHeader("Accept");

    final UAgentInfo detector = new UAgentInfo(userAgent, httpAccept);

    return detector.detectMobileQuick();
}

The UAgentInfo class has a bunch of methods to detect particular devices as well. Just replace detector.detectMobileQuick() for, for instance, detector.detectIphoneOrIpod(), detector.detectKindle(), etc.

UPDATE: If you use Spring, you might want to use its native implementation instead. Here is an example: http://spring.io/guides/gs/device-detection/

Solution 3

Using request.getHeader("User-Agent"). Here is a list of mobile browsers and their respective User-Agents.

Share:
16,394
Kyle
Author by

Kyle

Updated on June 13, 2022

Comments

  • Kyle
    Kyle almost 2 years

    Java Servlets - How do I detect if a user is from a mobile device?

    I'm using the TinyMCE javascript editor, and it doesn't work on the iphone. How can I detect if the user is coming from a mobile device?