㈠ 如何使用Java代码获取Android和ios移动终端Mac地址
通过设备开通wifi连接获取Mac地址是最可取的,代码如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 设备开通WiFi连接,通过wifiManager获取Mac地址
*
* @author 高焕杰
*/
public static String getMacFromWifi(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
State wifiState = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
if(wifiState == NetworkInfo.State.CONNECTED){//判断当前是否使用wifi连接
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) { //如果当前wifi不可用
wifiManager.setWifiEnabled(true);
}
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo.getMacAddress();
}
return null;
}
除了上面这种方法,网上还给出了另外两种方法:
1、通过调用Linux的busybox命令获取Mac地址:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 通过调用Linux的busybox命令获取Mac地址
*
* @author 高焕杰
*/
private static String getMacFromCallCmd(){
try {
String readLine = ;
Process process = Runtime.getRuntime().exec(busybox ifconfig);
BufferedReader bufferedReader = new BufferedReader (new InputStreamReader(process.getInputStream()));
while ((readLine = bufferedReader.readLine ()) != null) {//执行命令cmd,只取结果中含有HWaddr的这一行
if(readLine.contains(HWaddr)){
return readLine.substring(readLine.indexOf(HWaddr)+6, readLine.length()-1);
}
}
}catch(Exception e) { //如果因设备不支持busybox工具而发生异常。
e.printStackTrace();
}
return null;
}
注意:这种方法在Android Pad中可以准确获取到的Mac地址,但是在Android手机中无法准确获取到。
2、通过查询记录了MAC地址的文件(文件路径:“/proc/net/arp”)获取Mac地址:
?
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
/**
* 通过查询记录了MAC地址的文件(文件路径:“/proc/net/arp”)获取Mac地址
*
* @author 高焕杰
*/
private static String getMacFromFile(Context context){
String readLine =;
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(new File(/proc/net/arp)));
int rollIndex = 0;
while((readLine = bufferedReader.readLine())!=null){
if(rollIndex == 1){
break;
}
rollIndex = rollIndex + 1;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if(readLine !=null && readLine.length()>1){
String[] subReadLineArray = readLine.split( );
int rollIndex = 1;
for(int i = 0; i < subReadLineArray.length; ++i){
if(!TextUtils.isEmpty(subReadLineArray[i])){
if(rollIndex == 4){
return subReadLineArray[i];
}
rollIndex = rollIndex + 1;
}
}
}
return null;
}
注意:无论在Android Pad中还是在Android手机中,这种方法都无法准确获取到Mac地址。