Reputation: 4041
I am trying to detect "desktop", "mobile", and "tablet" from user agent strings. What I need is just these three rough categories. Brand and device names are not needed. Some examples of user agent I have are:
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)"
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36"
Is there any existing API can do this?
According to the very last sentence of this article, it seems that looking for keyword "mobi" in a user agent string can handle most cases. But it seems too easy to be true......
Upvotes: 5
Views: 14537
Reputation: 293
This might help.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DeviceTypeDetector {
public static String getDeviceType(String userAgent) {
String deviceType;
Pattern tabletPattern = Pattern.compile("(tablet|ipad|playbook|silk)|(android(?!.*mobi))", Pattern.CASE_INSENSITIVE);
Matcher tabletMatcher = tabletPattern.matcher(userAgent);
Pattern mobilePattern = Pattern.compile("(mobi|phone|blackberry|opera mini|fennec|minimo|symbian|psp|nintendo ds)", Pattern.CASE_INSENSITIVE);
Matcher mobileMatcher = mobilePattern.matcher(userAgent);
if (tabletMatcher.find()) {
deviceType = "tablet";
} else if (mobileMatcher.find()) {
deviceType = "mobile";
} else {
deviceType = "desktop";
}
return deviceType;
}
public static void main(String[] args) {
String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4537.110 Safari/537.36";
System.out.println(getDeviceType(userAgent));
}
}
Upvotes: 0
Reputation: 4605
I'm curious: Why does the device type matter?
Not trying to be snarky, but trying to understand a use case.
In Cordova you can check for this, but now sure about straight HTML. I which I have done for iOS before. I needed to do this to detect when I needed to add a 20px margin to the header of a page on a Cordova app, as iOS made this change several versions ago.
Here is how I did it:
if (parseFloat(window.device.version) >= 7.0 ) {
$allHeaders.css( "margin-top", "20px" );
}
Upvotes: 0
Reputation: 6119
You might use UADetector library that does just that. It has device categorization feature added since 0.9.10 version.
UADetector is a library to identify over 190 different desktop and mobile browsers and 130 other User-Agents like feed readers, email clients and multimedia players. In addition, even more than 400 robots like BingBot, Googlebot or Yahoo Bot can be identified.
Upvotes: 1