我的任务是实现一个在两部手机之间发送字符串的应用程序。客户端在提示用户输入服务器的Ip后打开与服务器的连接。为此,我使用了一个 EditText 字段和一个按钮。建立连接后,我希望显示一个新的 EditText 字段和一个按钮,并且用户能够输入字符串并单击按钮将这些字符串发送到服务器。服务器将在屏幕上显示消息。我应该为每个 EdiText&button 创建不同的活动吗?那将是2个活动。在这种情况下,我如何传递第一个活动将打开的套接字以建立与第二个活动的连接?是否可以仅在一项活动中做到这一点?考虑到每个活动都有 1 个关联的布局,我发现很难实现,
谢谢
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
}
private OnClickListener connectListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
Log.d("ClientActivity", serverIpAddress);
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
// where you issue the commands
out.println("message");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}