给Androidstudio的button添加一个andriodonClick事件点击这个事件调用一个子函数获取手机ip地址并且返回结果后接受返回结果在页面上显示出来特别要求要写出如何获取手机ip地址函数并且要写出他所需要的权限等
首先我们需要在AndroidManifest.xml文件中添加以下权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
这两个权限分别用于获取网络状态和访问网络。
然后在MainActivity.java文件中添加以下代码:
public class MainActivity extends AppCompatActivity {
private Button mButton;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = findViewById(R.id.button);
mTextView = findViewById(R.id.textview);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String ipAddress = getIpAddress();
mTextView.setText(ipAddress);
}
});
}
private String getIpAddress() {
String ipAddress = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ipAddress += "SiteLocalAddress: " + inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
e.printStackTrace();
ipAddress = "Something Went Wrong! " + e.toString();
}
return ipAddress;
}
}
在此代码中,我们先获取button和textView的实例,然后给button添加一个点击事件。在点击事件中,我们调用getIpAddress()函数获取当前手机的IP地址,并将其显示在textView上。
getIpAddress()函数中,我们使用了Java中的NetworkInterface类和InetAddress类来获取本地IP地址。我们通过循环枚举所有的网络接口,然后枚举每个网络接口的InetAddress,最后判断是否为本地IP地址。
需要注意的是,由于我们需要访问网络,因此我们需要在AndroidManifest.xml文件中添加上面提到的两个权限。
最后,在布局文件中添加一个Button和一个TextView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get IP Address" />
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:textAlignment="center"
android:textSize="24sp" />
</LinearLayout>
这样,我们就可以在点击Button时获取手机IP地址并在TextView上显示了。
原文地址: https://www.cveoy.top/t/topic/br75 著作权归作者所有。请勿转载和采集!