美文网首页
android6.0,7.0获取真实的蓝牙地址

android6.0,7.0获取真实的蓝牙地址

作者: 玉树林枫 | 来源:发表于2017-03-02 16:43 被阅读0次

    一开始是android6.0的问题,可以用下面的'MacUtils'类解决,但是当用华为mate 9时(android7.0),结果返回值又是空,只好另想办法。(android8.0下面方法已无效,暂时没想到解决办法)

    public class MacUtils {
    /**
     * 获取手机的MAC地址
     *
     * @return
     */
    public static String getMac() {
        String str = "";
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if ("".equals(macSerial)) {
            try {
                return loadFileAsString("/sys/class/net/eth0/address")
                        .toUpperCase().substring(0, 17);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return macSerial;
    }
    
    private static String loadFileAsString(String fileName) throws Exception {
        FileReader reader = new FileReader(fileName);
        String text = loadReaderAsString(reader);
        reader.close();
        return text;
    }
    
    private static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }
    }
    

    解决华为mate 9(不知道其他手机是否一样)

     /**
     * 获取蓝牙地址
     */
    public static String getMac(Context context) {
        return android.provider.Settings.Secure.getString(context.getContentResolver(), "bluetooth_address");
    }

    相关文章

      网友评论

          本文标题:android6.0,7.0获取真实的蓝牙地址

          本文链接:https://www.haomeiwen.com/subject/jtyzwttx.html