Android 获取Mac地址,在不同的安卓版本中获取的方法不同,参考网上代码后整理了以下,亲试完全可以,特此备份记录。
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
/**
* Created by Administrator on 2017/9/22.
*/
public class MacAddressManager {
/**
* 需要权限
*
*
*
*
*
*
*/
private static String TAG = "GetMac";
public static String getAdresseMAC(Context context) {
String strMac = "02:00:00:00:00:00";
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
strMac = getLocalMacAddressFromWifiInfo(context);
Log.e(TAG, "6.0以下 MAC = " + strMac);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N
&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
strMac = getMacfromMarshmallow();
Log.e(TAG, "6.0以上7.0以下:MAC = " + strMac);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
strMac = getMacFromHardware();
Log.e("MAC", "7.0以上:MAC = " + strMac);
}
return strMac;
}
/**
* 6.0以下 ,根据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;
String mac = "02:00:00:00:00:00";
if (context == null) {
return mac;
}
WifiManager wifi = (WifiManager) context.getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
if (wifi == null) {
return mac;
}
WifiInfo info = null;
try {
info = wifi.getConnectionInfo();
} catch (Exception e) {
}
if (info == null) {
return null;
}
mac = info.getMacAddress();
if (!TextUtils.isEmpty(mac)) {
mac = mac.toUpperCase(Locale.ENGLISH);
}
return mac;
}
/**
* android 6.0及以上、7.0以下 获取mac地址
* 如果是6.0以下,直接通过wifimanager获取
*
* @return
*/
public static String getMacfromMarshmallow() {
String WifiAddress = "02:00:00:00:00:00";
try {
WifiAddress = new BufferedReader(new FileReader(new File("/sys/class/net/wlan0/address"))).readLine();
} catch (IOException e) {
e.printStackTrace();
}
return WifiAddress;
}
/**
* 7.0 以上 遍历循环所有的网络接口,找到接口是 wlan0
* 必须的权限
*
* @return
*/
private static String getMacFromHardware() {
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 "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:", b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return "02:00:00:00:00:00";
}
}
获取其他信息
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import java.util.ArrayList;
import java.util.List;
/**
* 获取设备UniqueId = ANDROID_ID + Build.SERIAL
*
* @RequiresPermission(anyOf = {
* android.Manifest.permission.READ_PHONE_STATE,
* android.Manifest.permission.READ_SMS,
* android.Manifest.permission.READ_PHONE_NUMBERS,
* android.permission.READ_PHONE_STATE
* })
*
*/
@SuppressLint("HardwareIds")
public class DeviceInfo {
//移动运营商编号
private String NetworkOperator;
TelephonyManager tm;
Context context;
private boolean isPermission = true;
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE};
public DeviceInfo(Context context) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
isPermission = false;
int check = ContextCompat.checkSelfPermission(context, permissions[0]);
int check1 = ContextCompat.checkSelfPermission(context, permissions[1]);
if (check != PackageManager.PERMISSION_GRANTED && check1 != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
((Activity) context).requestPermissions(permissions, 1);
} else {
ActivityCompat.requestPermissions((Activity) context, permissions, 1);
}
}
}
this.context = context;
tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
}
/***
*
* @return s android id + 硬件序列号
*/
public String getUniqueId() {
return isPermission ? (Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ANDROID_ID) + Build.SERIAL) : "";
}
/**
* @return 返回唯一的设备ID
*/
@SuppressLint("MissingPermission")
public String getDeviceId() {
return isPermission ? tm.getDeviceId() : "";
}
/**
* 唯一的 App 签名密钥、用户和设备的每个组合
*
* @return 返回唯一的android ID
*/
@SuppressLint("HardwareIds")
public String getAndroidId() {
String id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
return isPermission ? id : "";
}
/**
* @return 返回 SIM 的序列号,如果适用的话。返回空,如果是不可用的。
*/
@SuppressLint("MissingPermission")
public String getSimSerialNumber() {
return isPermission ? tm.getSimSerialNumber() : "";
}
/**
* hardware serial number
*
* @return 硬件序列号
*/
public String getSerialNumber() {
return Build.SERIAL;
}
/**
* @return Returns the unique subscriber ID 返回唯一订阅方ID
*/
@SuppressLint("MissingPermission")
public String getSubscriberId() {
return tm.getSubscriberId();
}
/**
* @return 获取电话号码
*/
@SuppressLint("MissingPermission")
public String getNativePhoneNumber() {
String nativePhoneNumber = "N/A";
nativePhoneNumber = tm.getLine1Number();
return nativePhoneNumber;
}
//获取手机服务商信息
@SuppressLint("MissingPermission")
public String getProvidersName() {
String providersName = "N/A";
NetworkOperator = tm.getNetworkOperator();
//IMSI号前面3位460是国家,紧接着后面2位00 02是中国移动,01是中国联通,03是中国电信。
// Flog.d(TAG,"NetworkOperator=" + NetworkOperator);
if (NetworkOperator.equals("46000") || NetworkOperator.equals("46002")) {
providersName = "中国移动";//中国移动
} else if (NetworkOperator.equals("46001")) {
providersName = "中国联通";//中国联通
} else if (NetworkOperator.equals("46003")) {
providersName = "中国电信";//中国电信
}
return providersName;
}
@SuppressLint("MissingPermission")
public String getPhoneInfo() {
StringBuffer sb = new StringBuffer();
sb.append("\n手机号 = " + tm.getLine1Number());
sb.append("\nNetworkOperator = " + tm.getNetworkOperator());//移动运营商编号
sb.append("\nNetworkOperatorName = " + tm.getNetworkOperatorName());//移动运营商名称
sb.append("\nSimCountryIso = " + tm.getSimCountryIso());
sb.append("\nSimOperator = " + tm.getSimOperator());
sb.append("\nSimOperatorName = " + tm.getSimOperatorName());
sb.append("\nSubscriberId(IMSI) = " + tm.getSubscriberId());
sb.append("\n");
return sb.toString();
}
/**
* getSerialNumber
*/
public List displayDevice() {
List list = new ArrayList<>();
list.add("UniqueId:" + getUniqueId());
list.add("DeviceId:" + getDeviceId());
list.add("AndroidId:" + getAndroidId());
list.add("SIM 的序列号:" + getSimSerialNumber());
list.add("硬件序列号(serial number):" + getSerialNumber());
list.add("unique subscriber ID:" + getSubscriberId());
return list;
}
}