首先,在 button 的 XML 布局中添加 android:onClick 属性,例如:

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="获取 MAC 和 IP 地址"
    android:onClick="getMacAndIPAddress" />

然后,在对应的 Activity 中添加 getMacAndIPAddress() 方法,如下所示:

public void getMacAndIPAddress(View view) {
    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    String macAddress = wifiInfo.getMacAddress();
    int ipAddress = wifiInfo.getIpAddress();
    String ipAddressStr = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
    Log.d("MainActivity", "MAC 地址:" + macAddress);
    Log.d("MainActivity", "IP 地址:" + ipAddressStr);
    Toast.makeText(this, "MAC 地址:" + macAddress + "\nIP 地址:" + ipAddressStr, Toast.LENGTH_LONG).show();
}

这个方法使用了 Android 的 WifiManagerWifiInfo 类来获取当前连接的 WiFi 的 MAC 地址和 IP 地址,并通过 Log 输出到控制台,通过 Toast 显示在屏幕上。

需要注意的是,使用 WifiManagerWifiInfo 类需要在 AndroidManifest.xml 中添加以下权限:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

标准库:

  • Java SE 7 API 文档:https://docs.oracle.com/javase/7/docs/api/
  • Android 开发者官网:https://developer.android.com/
Android Studio Button 点击获取手机 MAC 和 IP 地址

原文地址: https://www.cveoy.top/t/topic/mQ32 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录