Tuesday 12 February 2013

Android Detection with JavaScript or PHP

Hello Friends

You have a web application and you want to detect that if your Application is opened from android device than it will be redirect to any other URL that will be Android compatible.This is a good solution for you.

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:

[sourcecode language="php"]
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.viralsolani.co';
}

[/sourcecode]

The PHP


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

[sourcecode language="php"]
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') !== false){// && stripos($ua,'mobile') !== false) {
header('Location: http://android.viralsolani.co');
exit();
}
[/sourcecode]

Bonus! .htaccess Detection



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

[sourcecode language="php"]
RewriteCond %{HTTP_USER_AGENT} ^.*Android.*$
RewriteRule ^(.*)$ http://android.viralsolani.co [R=301]
[/sourcecode]

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

Resource :

http://davidwalsh.name/detect-android

Thanks

 

No comments:

Post a Comment