버전이 올라가면서 기존 소스코드에 문제가 있어서 테스트 해본 소스코드


우선 안드로이드 메니페스트에

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
정의 해주고
아래 소스코드 처럼 intf.getHardwareAddress(); 에서 하드웨어 주소를 가져와서 처리하면 사용가능합니다.

public class MainActivity extends AppCompatActivity {

Button btn1 = findViewById(R.id.btn1);
TextView text1 = findViewById(R.id.text1);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);



Button.OnClickListener mClickListener = new View.OnClickListener(){
@Override
public void onClick(View v) {

// text1.setText(getMACAddress().toString());
text1.setText(macAddress);



}
};


}


public static String getMACAddress(String interfaceName) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (interfaceName != null) {
if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac==null) return "";
StringBuilder buf = new StringBuilder();
for (int idx=0; idx<mac.length; idx++)
buf.append(String.format("%02X:", mac[idx]));
if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
return buf.toString();
}
} catch (Exception ex) { } // for now eat exceptions
return "";
}
public String macAddress = getMACAddress("wlan0");

}


반응형

+ Recent posts