Android获取Mac地址-适配所有版本
【摘要】
最近由于项目需要MAC地址的记录,搞了一个通用的适配类,目前经过测试可以适配Android所有版本,我测试过的设备系统Android 4 5 6 7 7+都可以获取到,废话不多说直接上代码,简洁:
该类...
最近由于项目需要MAC地址的记录,搞了一个通用的适配类,目前经过测试可以适配Android所有版本,我测试过的设备系统Android 4 5 6 7 7+都可以获取到,废话不多说直接上代码,简洁:
该类分为三类:Android6.0以下、6.0以上7.0以下、7.0以上
首先是获取MAC的整合方法:
public static String getMac(Context context) {
String strMac = null;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
Log.e("=====", "6.0以下");
Toast.makeText(context, "6.0以下", Toast.LENGTH_SHORT).show();
strMac = getLocalMacAddressFromWifiInfo(context);
return strMac;
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N
&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Log.e("=====", "6.0以上7.0以下");
Toast.makeText(context, "6.0以上7.0以下", Toast.LENGTH_SHORT).show();
strMac = getMacAddress(context);
return strMac;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.e("=====", "7.0以上");
if (!TextUtils.isEmpty(getMacAddress())) {
Log.e("=====", "7.0以上1");
Toast.makeText(context, "7.0以上1", Toast.LENGTH_SHORT).show();
strMac = getMacAddress();
return strMac;
} else if (!TextUtils.isEmpty(getMachineHardwareAddress())) {
Log.e("=====", "7.0以上2");
Toast.makeText(context, "7.0以上2", Toast.LENGTH_SHORT).show();
strMac = getMachineHardwareAddress();
return strMac;
} else {
Log.e("=====", "7.0以上3");
Toast.makeText(context, "7.0以上3", Toast.LENGTH_SHORT).show();
strMac = getLocalMacAddressFromBusybox();
return strMac;
}
}
return "02:00:00:00:00:00";
}
6.0以下方法,Google提供的公有方法,需要权限
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
/**
* 根据wifi信息获取本地mac
* @param context
* @return
*/
public static String getLocalMacAddressFromWifiInfo(Context context){
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo winfo = wifi.getConnectionInfo();
String mac = winfo.getMacAddress();
return mac;
}
android 6.0及以上、7.0以下
android 6.0以后 将不再能通过 wifimanager 获取mac,获取到的mac将是固定的:02:00:00:00:00:00 。
然而我开发的sdk就是通过wifimanager获取的mac。
android sdk后来做了6.0适配,通过cat /sys/class/net/wlan0/address,可以在6.0上获取mac地址。
/**
* android 6.0及以上、7.0以下 获取mac地址
*
* @param context
* @return
*/
public static String getMacAddress(Context context) {
// 如果是6.0以下,直接通过wifimanager获取
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
String macAddress0 = getMacAddress0(context);
if (!TextUtils.isEmpty(macAddress0)) {
return macAddress0;
}
}
String str = "";
String macSerial = "";
try {
Process pp = Runtime.getRuntime().exec(
"cat /sys/class/net/wlan0/address");
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (; null != str; ) {
str = input.readLine();
if (str != null) {
macSerial = str.trim();// 去空格
break;
}
}
} catch (Exception ex) {
Log.e("----->" + "NetInfoManager", "getMacAddress:" + ex.toString());
}
if (macSerial == null || "".equals(macSerial)) {
try {
return loadFileAsString("/sys/class/net/eth0/address")
.toUpperCase().substring(0, 17);
} catch (Exception e) {
e.printStackTrace();
Log.e("----->" + "NetInfoManager",
"getMacAddress:" + e.toString());
}
}
return macSerial;
}
private static String getMacAddress0(Context context) {
if (isAccessWifiStateAuthorized(context)) {
WifiManager wifiMgr = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = null;
try {
wifiInfo = wifiMgr.getConnectionInfo();
return wifiInfo.getMacAddress();
} catch (Exception e) {
Log.e("----->" + "NetInfoManager",
"getMacAddress0:" + e.toString());
}
}
return "";
}
/**
* Check whether accessing wifi state is permitted
*
* @param context
* @return
*/
private static boolean isAccessWifiStateAuthorized(Context context) {
if (PackageManager.PERMISSION_GRANTED == context
.checkCallingOrSelfPermission("android.permission.ACCESS_WIFI_STATE")) {
Log.e("----->" + "NetInfoManager", "isAccessWifiStateAuthorized:"
+ "access wifi state is enabled");
return true;
} else
return false;
}
private static String loadFileAsString(String fileName) throws Exception {
FileReader reader = new FileReader(fileName);
String text = loadReaderAsString(reader);
reader.close();
return text;
}
private static String loadReaderAsString(Reader reader) throws Exception {
StringBuilder builder = new StringBuilder();
char[] buffer = new char[4096];
int readLength = reader.read(buffer);
while (readLength >= 0) {
builder.append(buffer, 0, readLength);
readLength = reader.read(buffer);
}
return builder.toString();
}
android 7.0及以上
android 7.0 后,通过上述适配的方法,将获取不到mac地址。
经过调研和测试,7.0上仍有办法回去mac地址:
总共分为三种方式:
(1)通过ip地址来获取绑定的mac地址
(2)扫描各个网络接口获取mac地址
(3)通过busybox获取本地存储的mac地址
代码如下:
/**
* 根据IP地址获取MAC地址
*
* @return
*/
public static String getMacAddress() {
String strMacAddr = null;
try {
// 获得IpD地址
InetAddress ip = getLocalInetAddress();
byte[] b = NetworkInterface.getByInetAddress(ip)
.getHardwareAddress();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < b.length; i++) {
if (i != 0) {
buffer.append(':');
}
String str = Integer.toHexString(b[i] & 0xFF);
buffer.append(str.length() == 1 ? 0 + str : str);
}
strMacAddr = buffer.toString().toUpperCase();
} catch (Exception e) {
}
return strMacAddr;
}
/**
* 获取移动设备本地IP
*
* @return
*/
private static InetAddress getLocalInetAddress() {
InetAddress ip = null;
try {
// 列举
Enumeration<NetworkInterface> en_netInterface = NetworkInterface
.getNetworkInterfaces();
while (en_netInterface.hasMoreElements()) {// 是否还有元素
NetworkInterface ni = (NetworkInterface) en_netInterface
.nextElement();// 得到下一个元素
Enumeration<InetAddress> en_ip = ni.getInetAddresses();// 得到一个ip地址的列举
while (en_ip.hasMoreElements()) {
ip = en_ip.nextElement();
if (!ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1)
break;
else
ip = null;
}
if (ip != null) {
break;
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return ip;
}
/**
* 获取本地IP
*
* @return
*/
private static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
/**
* android 7.0及以上 (2)扫描各个网络接口获取mac地址
*
*/
/**
* 获取设备HardwareAddress地址
*
* @return
*/
public static String getMachineHardwareAddress() {
Enumeration<NetworkInterface> interfaces = null;
try {
interfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
String hardWareAddress = null;
NetworkInterface iF = null;
if (interfaces == null) {
return null;
}
while (interfaces.hasMoreElements()) {
iF = interfaces.nextElement();
try {
hardWareAddress = bytesToString(iF.getHardwareAddress());
if (hardWareAddress != null)
break;
} catch (SocketException e) {
e.printStackTrace();
}
}
return hardWareAddress;
}
/***
* byte转为String
*
* @param bytes
* @return
*/
private static String bytesToString(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null;
}
StringBuilder buf = new StringBuilder();
for (byte b : bytes) {
buf.append(String.format("%02X:", b));
}
if (buf.length() > 0) {
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}
/**
* android 7.0及以上 (3)通过busybox获取本地存储的mac地址
*
*/
/**
* 根据busybox获取本地Mac
*
* @return
*/
public static String getLocalMacAddressFromBusybox() {
String result = "";
String Mac = "";
result = callCmd("busybox ifconfig", "HWaddr");
// 如果返回的result == null,则说明网络不可取
if (result == null) {
return "网络异常";
}
// 对该行数据进行解析
// 例如:eth0 Link encap:Ethernet HWaddr 00:16:E8:3E:DF:67
if (result.length() > 0 && result.contains("HWaddr") == true) {
Mac = result.substring(result.indexOf("HWaddr") + 6,
result.length() - 1);
result = Mac;
}
return result;
}
private static String callCmd(String cmd, String filter) {
String result = "";
String line = "";
try {
Process proc = Runtime.getRuntime().exec(cmd);
InputStreamReader is = new InputStreamReader(proc.getInputStream());
BufferedReader br = new BufferedReader(is);
while ((line = br.readLine()) != null
&& line.contains(filter) == false) {
result += line;
}
result = line;
} catch (Exception e) {
e.printStackTrace();
}
return result;
- 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
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
文章来源: chengsy.blog.csdn.net,作者:程思扬,版权归原作者所有,如需转载,请联系作者。
原文链接:chengsy.blog.csdn.net/article/details/103815638
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)