这篇文章主要介绍使用Java代码获取Android移动终端Mac地址的案例,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
如何使用Java代码获取Android移动终端Mac地址:
通过设备开通WiFi连接获取Mac地址是最可取的,代码如下:
/**
* 设备开通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地址:
/**
* 通过调用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地址:
/**
* 通过查询记录了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地址。
以上是“使用Java代码获取Android移动终端Mac地址的案例”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://www.xuebuyuan.com/3268992.html