Android携帯電話MACを取得する方法
3208 ワード
Android携帯電話MACの実装案を取得し、参考にしてください.ハハハ!他にもっと優れた解決策はありますか?
高バージョンではWiFiがオフの場合、MAC`/**が取得できません.*param context * @return */
`
高バージョンではWiFiがオフの場合、MAC`/**が取得できません.*param context * @return */
public static String getWlanMac(Context context){
String mac = getWlanMacWifiManager(context);
if(mac == null){
//
mac = getWlanMacLocalAddress();
if(mac == null){
// java
mac = getWlanMacInterface();
if(mac == null){
//
mac = Pref.getString("wlan_mac_cached", context);
}
}
}
if(mac != null){
// mac , ; MAC
Pref.saveString("wlan_mac_cached", mac, context);
}
return mac;
/**
* WifiManager MAC;
* @param context
* @return
*/
public static String getWlanMacWifiManager(Context context){
Log.i("DeviceUtil","get mac by WifiManager...");
String mac = null;
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
boolean isWifiEnabled = wifiManager.isWifiEnabled();
if(!isWifiEnabled){
//6.0 ,
wifiManager.setWifiEnabled(true);
}
if (isWifiEnabled) {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo != null) {
mac = wifiInfo.getMacAddress();
if(CheckUtils.isMacRight(mac)){
Log.i("DeviceUtil","mac = " + mac);
return mac;
}else{
mac = null;
}
}
}
return mac;
}
/**
* MAC;
* @param context
* @return
*/
public static String getWlanMacLocalAddress(){
Log.i("DeviceUtil","get mac by local address...");
String mac = null;
String path = "/sys/class/net/wlan0/address";
File wlan0 = new File(path);
if(wlan0.exists() && wlan0.isFile()){
mac = execCmd("cat " + path);
if (CheckUtils.isMacRight(mac)) {
return mac;
}else{
mac = null;
}
}
return mac;
}
private static String getWlanMacInterface() {
Log.i("DeviceUtil","get mac by new interface..." );
String mac = null;
try {
List all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) {
continue;
}
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return mac;
}
StringBuilder builder = new StringBuilder();
for (byte b : macBytes) {
builder.append(String.format("%02X:",b));
}
if (builder.length() > 0) {
builder.deleteCharAt(builder.length() - 1);
}
mac = builder.toString();
Log.i("DeviceUtil","mac = " + mac);
}
} catch (Exception e) {
e.printStackTrace();
}
return mac;
}
`