给android studio的一个按钮添加android onClick事件函数如下获取手机mac和ip地址并且输出
以下是一个样例代码,可以在Android Studio中使用:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get MAC and IP Address"
android:onClick="getMacAndIpAddress" />
在对应的Activity中,添加以下函数:
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 ipAddressString = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
Toast.makeText(this, "MAC Address: " + macAddress + "\nIP Address: " + ipAddressString, Toast.LENGTH_LONG).show();
}
这个函数首先获取了WifiManager的实例,并用它来获取当前连接的Wifi信息。然后,它从WifiInfo对象中获取了MAC地址和IP地址,并将它们格式化为字符串。最后,函数使用Toast来显示这些信息。当用户点击按钮时,这个函数就会被调用。
原文地址: https://www.cveoy.top/t/topic/bleO 著作权归作者所有。请勿转载和采集!