Android Detection with JavaScript or PHP

I've noticed that two of my blog posts continue to get more popular each week:  iPad Detection with JavaScript or PHP and iPhone and iPad detection with JavaScript or PHP. What's obvious is that Android development is a hot topic that will only grow.  Here are a few methods by which you can detect iOS' main competitor:  Android.

The JavaScript

Searching the user agent string for "Android" is the quickest method:

var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
	// Do something!
	// Redirect to Android-site?
	window.location = 'http://android.davidwalsh.name';
}

The PHP

Again, we'll use PHP's strstr function to search for Android in the user agent:

$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') !== false) { // && stripos($ua,'mobile') !== false) {
	header('Location: http://android.davidwalsh.name');
	exit();
}

Bonus!  .htaccess Detection

We can even use .htaccess directives to detect and react to Android devices!

RewriteCond %{HTTP_USER_AGENT} ^.*Android.*$
RewriteRule ^(.*)$ http://android.davidwalsh.name [R=301]

And there you have it:  three different Android device detection!  Have fun with your mobile development!


Comments

  1. Erik Edgren

    Very neat solution! :D I love the detection via .htaccess. Thanks a lot!

  2. Blaine

    Depending on how you have your site setup, you may also want to detect that it’s not already at the android address.

    Would be useful if you are just theme switching, instead of going to a completely different website.

  3. Jonah Bron

    Very nice. However, the PHP solution is slightly flawed. Strstr() returns the position at which the “needle” was found, or boolean false if it’s not found at all. If “Android” was found at the very beginning of the string, it would return 0, which evaluates to false. This is obviously incorrect. The solution is to make a typed check.

    if(strstr($_SERVER['HTTP_USER_AGENT'],'Android') !== false) {

    Also, it might be a good idea to use stristr(), for case insensitivity.

    • Jonathan

      Nice tip. However, you might wanna use stripos() since it’s faster.

    • David Walsh

      Updated guys. Android never appears at the beginning of the UA strings, but it’s good to keep good practices.

  4. Distorzija

    Absolutely fantastic, David! Keep up with the good work. Thank you for sharing!

  5. Andi

    Very nice article!

    For a detailed detection with php check out the tera-wurfl project.
    I’m using it in my projects to detect all mobile devices.

  6. Salwars

    Really nice post.. thanks for sharing all these..

  7. Greg

    There are a lot of people who are against user agent detection (preferring something more universal such as window size detection with CSS media queries, for example).

    However, I think there’s still a place for it if you architect your site properly. You’re never going to detect the string “Android” in a non-Android device, for example.

    As long as there’s a fallback for when no “sure-fire” match is made, I don’t see why we can’t add UA detection as an enhancement to our sites, as long as we ensure no false positives and that the experience isn’t broken by detecting UA.

    (also worth noting: people should always have the option to switch to “full/standard” website; if they feel like swiping and zooming around, let them!)

    • fabsn182

      Nice post but why should you deliver an android optimized page for somebody using an android tablet with a screen size just like the iPad?

  8. Robert

    I agree with Andi. The Tera-WURFL project is the way to go. the amount of detail you can get from each device is simply amazing. so much more than user agents and window size, but playback capabilities, versions, etc.

  9. fabsn182

    Nice but I think you shouldn’t use browser but feature detection. It might be possible that users won’t use the android stock browser and also change the user agent to iPhone/iPad or desktop PC (Firefox or IE).

    • David Walsh

      I’m open to suggestions for feature detection on the client side. What would you recommend?

  10. Mathias Bynens

    User agent sniffing must die. Nice job advocating this bad practice.

    • David Walsh

      Thank you so much Mathias!

    • Stephen J. Fuhry

      If you don’t want people to know your user agent, then don’t tell them your user agent. That’s like complaining about davidwalsh.com publishing the comment you just willfully posted.

  11. John-David Dalton

    Android’s dev blog points out that simply looking for “Android” in the UA might cause you to serve a mobile version of the site to a large-form-factor Android device.

  12. Bad

    When will if(isAndroid) evaluate to true in your examples?

    Almost always (-1 anyone?)!! Badly implemented bad practice!

  13. Ramaraju Ramakanth

    Awesome…Very helpful..thanks

  14. Richard

    Top Stuff David. As an aside, you can use a service like http://www.handsetdetection.com to do Android detection as well. Handset Detection can also tell the difference between tablets & handsets – which can be handy for redirection. (disclaimer : I work there).

    To allow visitors to go from your mobile site back to your standard site check the http_referrer. If the referrer is your mobile site then disable the check. :-)

  15. Gareth Poole

    Thanks for sharing! Just what I needed :-)

  16. Pritesh Loke

    Simple solution

  17. Bryce

    Thanks for the code! What those ‘bad practice’ nay-sayers are missing is that many companies have mobile versions of their websites which need to detect mobile browsers.

    • David Mark

      No, the “naysayers” are likely not in that unfortunate group (those that have painted themselves into a corner with bloated GP libraries and other poor practices).

      And they do not “need” to detect any such thing. Think.

  18. Keegan Street

    Guys, this is not a good way to serve an alternate site for mobile. It doesn’t matter what the name or user agent of the device is. What matters is if the device has the capabilities to perform the things you need it to do.

    If a new mobile phone gets released tomorrow that does everything an Android can do, it should see your mobile website too no matter what user agent it has.

    For a better solution see modernizr. http://www.modernizr.com/

  19. David Mark

    Browser sniffing is a stupid, error-prone and reviled practice, “backed” by a decade of failures. Doing it on the server side is completely clueless as you could very well be talking to a proxy.

    http://www.jibbering.com/faq/notes/detect-browser/

    And what does the string “Android” imply? Absolutely nothing, not even that the screen is small (use media queries to detect that).

    Do not use this code (or code that resembles it) under any circumstances.

    • Bryce

      Every situation is different, and to say a method is “Stupid” because it is not optimal for your situation is, well, Stupid!

      Grow up and think outside of your own circumstances, for everyone’s sake ;)

  20. Chris Allinson

    The navigator.userAgent value can not determine whether or not it is an android tablet, or an android smartphone. Detecting window.innerHeight or screen.height won’t help either as HD phones have similar resolutions to non-HD tablets!

    Is there a better solution?!?

    I need to forward the user to the mobile site when they are on a smartphone, while tablet users would see the normal “desktop” version of the site.

  21. David Walsh

    A good read about using media queries to detect device/browser:

    http://www.cloudfour.com/css-media-query-for-mobile-is-fools-gold/

    They aren’t always as reliable as preached.

  22. David Walsh

    I will also point out that before completing this post, I checked jQuery Mobile, Sencha Touch, Phone Gap, etc. They all appear to use UA sniffs. I’ve also not yet been provided a better solution by anyone. I’m more than receptive to receiving one.

  23. John-David Dalton

    To counter the older post nay-saying media queries I’ll point to a newer one promoting them: http://www.html5rocks.com/mobile/mobifying.html

    Also, the compat tables referenced by the cloudfour article are ~2yrs old. Media queries should work great for Android devices now.

    Android’s own dev site has a post on them+viewport-metas+JS: http://developer.android.com/guide/webapps/targeting.html

    • Jason Grigsby

      FWIW, the article referenced–the one I wrote–was written on August 3, 2010, not two years ago. The compat tables referenced were tests conducted on real devices during the period of August 1-3 of last year.

      Files downloading for display:none img tags is still an issue on iOS. Hence the responsive images js code that the Filament Group has developed for the Boston Globe project they are doing with Ethan Marcotte:
      https://github.com/filamentgroup/Responsive-Images

      FWIW, most major sites delivering mobile optimized content are still using some aspect of server-side detection–usually in conjunction with client-side feature detection. I know from conversations with Google that they do this and Facebook has been very open about their use of device detection:
      http://www.facebook.com/notes/facebook-engineering/crowdsourcing-mobile-device-capabilities/441195668919
      http://www.facebook.com/note.php?note_id=10150122073713920

      I echo the comments of those who note the specific requirements of a project or product–particularly what devices you need to support–may necessitate different tools. Like most things, it depends.

    • John-David Dalton

      Jason, I wrote that the *compat tables referenced are ~2yrs old*.

      You should also note that Google/Facebook have gobs of devs to monitor and tweak their UA sniffs when new browsers/devices come out.

      As I’ve said before, UA sniffing should be a last resort not a knee-jerk first.

    • Jason Grigsby

      John-David,

      Just stumbled back on this post and your response. I had forgotten about the link to PPK’s tables. I thought you were referring to my tests of mediaqueries, not the link. My mistake.

      -Jason

  24. Douglas

    David, You rock! Thanks for the free code.

  25. Brent

    Thanks for the snippet. Yeah the mobile web is a tricky beast. Not easy to find the most “correct” path. Context is everything.

    “Were I to invoke logic, logic clearly dictates that the needs of the many outweigh the needs of the few.”

  26. neil

    Using the default browser on my HTC Desire no user_agent identification code works.

  27. Alan Davies

    I think some are missing the point. The detection isn’t there just to redirect to a custom Android page/site. It can be used to enable or disable page elements. For example TinyMCE editor works great in iPhone and iPad, but dies a death on my HTC Sensation. Therefore, I need to ensure that I can disable TinyMCE on Android and serve a different text input.

  28. Ben Walters

    This is only ‘bad practice’ with it’s implementation. If you are using this to re-direct to mobile sites, then this being ‘bad-practice’ is the least of your worries (Media Queries, .htaccess… come on!?).

    BUT, if you are using this to, for example, serve up a link to the android market for android users, and a link to the AppStore for IOS devices, using the us sniff to hide and show elements, then i fail to see any kind of poor implementation practices. This is a seemingly 2D snippet, with a huge range of applications.

    Get inventive!

  29. Kiss

    Best user agent detector in the world here http://tinytop.mobi Last update 02.02.2012 Please make a topic about this.

  30. Robocat

    The best cross-browser way I have found to detect touch devices is to use:

    var isTouchDevice = (‘ontouchstart’ in document.documentElement);

  31. Robocat

    However the above doesn’t allow the user to use the “Request desktop site” feature of 4.0 and Chrome Mobile.


Be Heard!

Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!

Name*:
Email*:
Website: