顯示乙太網Mac地址的方法

liuminx發表於2020-07-02
先通過地址判斷:/sys/class/net/eth0/address ,常由於許可權原因而無法訪問;
故還需使用另外一種方式讀取

@SuppressLint("HardwareIds")
@Override
protected void updateConnectivity() {
    try (BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(
            "/sys/class/net/eth0/address")))) {
        String ethernetMacAddress = input.readLine();
        mEthernetMacAddress.setSummary(ethernetMacAddress);
    } catch (IOException ex) {
        final String macAddress = getEthernetMacAddress();

        if (TextUtils.isEmpty(macAddress)) {
            mEthernetMacAddress.setSummary(mUnavailable);
        } else {
            mEthernetMacAddress.setSummary(macAddress);
        }

    }
}

private Network getFirstEthernet() {
    final Network[] networks = mCM.getAllNetworks();
    for (final Network network : networks) {
        NetworkInfo networkInfo = mCM.getNetworkInfo(network);
        if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
            return network;
        }
    }
    return null;
}

private String getEthernetMacAddress() {
    final Network network = getFirstEthernet();
    return network != null ? mCM.getNetworkInfo(network).getExtraInfo() : null;
}

相關文章