Detectar Android con Javascript o 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.

JavaScript

Searching the user agent string for “Android” is the quickest method:

copyvar 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';
}

PHP

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

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

.htaccess Detection

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

copyRewriteCond %{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!

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s