您的位置:首页 > 移动开发 > Android开发

如何使用Java代码获取Android移动终端Mac地址

2015-01-09 17:16 746 查看
        快下班了,现在总结一下如何使用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地址。        【0分下载示例
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: