我写了android代码在EditText中获取用户的IP地址,然后手机与用户在EditText中获取的电脑ip通信。
这是我的代码,当我点击按钮时没有任何效果:
public class MainActivity extends Activity {
Button b;
EditText et;
TextView tv;
private Socket socket;
int PORT = 4003;
String HOST; //HOST = " 192.168.2.1"
private Handler textview_handler_thread;
class ClientThread implements Runnable {
@Override
public void run()
{
try {
socket = new Socket(HOST, PORT);
Message msg = null;
while(true) {
msg = textview_handler_thread.obtainMessage();
msg.obj = "Process Completed Succesfully";
textview_handler_thread.sendMessage(msg);
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
et = (EditText) findViewById(R.id.editText1);
HOST = et.getText().toString();
new Thread(new ClientThread()).start();
textview_handler_thread = new Handler() {
public void handleMessage(Message msg) {
Object o = msg.obj;
if (o == null)
o = "";
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(o.toString());
}
};
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
try {
DataOutputStream output_to_server = new DataOutputStream(socket.getOutputStream());
String client_str = et.getText().toString();
output_to_server.writeBytes(client_str);
output_to_server.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
HOST 变量中的问题应该包含来自用户的 IP 地址。 一开始我写了 HOST = "192.168.2.1"; 但现在我希望用户这样做。
注意:如果我写 HOST = "192.168.2.1";它被成功执行。当我指定 HOST 的值来编辑文本时无法与计算机通信,为什么?
最佳答案
那是因为您在 OnCreate 时将值赋给了 HOST。那时,那个文本框还是空的。
您可能想在 OnClick 事件中执行此操作
String client_str = et.getText().toString();
HOST = Client_str;
此时,HOST 应包含用户键入的 IP 地址。此外,您不得在 OnCreate 处启动线程。那时HOST还什么都没有。
关于java android编程..从用户获取ip地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36658528/