java 获取设备信息

这篇文章主要讲解 java 获取设备信息

// \b 是单词边界(连着的两个(字母字符 与 非字母字符) 之间的逻辑上的间隔),
// 字符串在编译时会被转码一次,所以是 “\b”
// \B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i" + "|windows (phone|ce)|blackberry" + "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
+ "|laystation portable)|nokia|fennec|htc[-_]" + "|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
static String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser" + "|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";

/* 移动设备正则匹配:手机端、平板 */
static Pattern phonePat = Pattern.compile( phoneReg, Pattern.CASE_INSENSITIVE );
static Pattern tablePat = Pattern.compile( tableReg, Pattern.CASE_INSENSITIVE );

/**
* 检测是否是移动设备访问
*
* @Title: check
* @Date : 2014-7-7 下午01:29:07
* @param userAgent
* 浏览器标识
* @return true:移动设备接入,false:pc端接入
*/
protected boolean check( String userAgent )
{
if ( null == userAgent )
{
userAgent = "";
}
/* 匹配 */
Matcher matcherPhone = phonePat.matcher( userAgent );
Matcher matcherTable = tablePat.matcher( userAgent );
if ( matcherPhone.find() || matcherTable.find() )
{
return(true);
} else {
return(false);
}
}


/**
* 获取设备名称
* @param userAgent
* @return
*/
protected String getDeviceName( String userAgent )
{
if ( null == userAgent )
{
userAgent = "";
}
/* 匹配 */
Matcher matcherPhone = phonePat.matcher( userAgent );
Matcher matcherTable = tablePat.matcher( userAgent );
if ( matcherPhone.find() )
{
return(matcherPhone.group() );
} else if ( matcherTable.find() )
{
return(matcherTable.group() );
} else {
return("pc");
}
}


String ua = request.getHeader( "User-Agent" ).toLowerCase();
String deviceType = this.check( ua ) ? "mobile" : "pc";
String deviceName = this.getDeviceName( ua );