效果演示:
实现步骤
一、布局页面activity_inet_address.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="5dp" tools:context=".InetAddressActivity"> <EditText android:id="@+id/edit_address" android:layout_width="match_parent" android:layout_height="50dp" android:background="@drawable/edit_style" android:text="www.163.com" /> <Button android:id="@+id/btn_hostName_check" android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginTop="5dp" android:text="检查主机名" android:textColor="@color/black" android:textSize="20sp" /> <TextView android:id="@+id/tv_desc" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/black" android:textSize="15sp" /> </LinearLayout>
二、InetAddressActivity类,实现根据用户输入的主机名,检查是否可以连接,并且显示主机名,和ip地址,代码中已经给出了详细的注释。
public class InetAddressActivity extends AppCompatActivity implements View.OnClickListener { private EditText edit_address; private TextView tv_desc; private Button btn_hostName_check; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inet_address); edit_address = findViewById(R.id.edit_address); tv_desc = findViewById(R.id.tv_desc); btn_hostName_check = findViewById(R.id.btn_hostName_check); btn_hostName_check.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_hostName_check: String hostName = edit_address.getText().toString(); //开启子线程 检查主机名 new CheckThread(hostName).start(); break; default: break; } } //创建一个检查结果的接收器Handler private Handler handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message msg) { tv_desc.setText("主机检查结果如下:\n" + msg.obj); return true; } }); private class CheckThread extends Thread { private String hostName; public CheckThread(@NonNull String name) { hostName = name; } @Override public void run() { //获得一个默认消息对象 Message message = Message.obtain(); try { //根据主机名获取主机名称对象 InetAddress inetAddress = InetAddress.getByName(hostName); //检查该主机在规定时间内能否连上 boolean isReachable = inetAddress.isReachable(5000); String desc = (isReachable) ? "可以连接" : "无法连接"; if (isReachable) { desc = String.format("%s\n主机名为:%s\n主机地址为:%s", desc, inetAddress.getHostName(), inetAddress.getHostAddress()); message.what = 0; //消息类型 message.obj = desc;//消息描述 } } catch (Exception e) { e.printStackTrace(); message.what = -1; //消息类型 message.obj = e.getMessage(); //消息描述 } // 向接收处理器发送检查结果消息 handler.sendMessage(message); } } }