protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ipEditText = findViewById(R.id.ipEditText); portEditText = findViewById(R.id.portEditText); Button connectButton = findViewById(R.id.connectButton); connectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String ip = ipEditText.getText().toString(); int port = Integer.parseInt(portEditText.getText().toString()); new ConnectTask().execute(ip, String.valueOf(port)); } }); Button sendMessageButton = findViewById(R.id.sendMessageButton); sendMessageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showSendMessageDialog(); } });我想加入两个按钮向端口发送固定字符串
时间: 2024-02-14 08:10:29 浏览: 62
Android this与Activity.this的区别
好的,您可以在 sendMessageButton 的点击事件处理方法中执行发送固定字符串的操作。具体实现方式取决于您使用的通信协议和库。以下是一个使用 Java Socket 实现发送字符串的示例代码:
```
Button sendHelloButton = findViewById(R.id.sendHelloButton);
sendHelloButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage("Hello");
}
});
Button sendWorldButton = findViewById(R.id.sendWorldButton);
sendWorldButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage("World");
}
});
private void sendMessage(String message) {
new Thread(new Runnable() {
@Override
public void run() {
try {
String ip = ipEditText.getText().toString();
int port = Integer.parseInt(portEditText.getText().toString());
Socket sock = new Socket(ip, port);
OutputStream out = sock.getOutputStream();
out.write(message.getBytes());
out.flush();
out.close();
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
```
请注意,在这个示例中,我们在新的线程中执行发送操作,以避免阻塞 UI 线程。同时,您需要在 AndroidManifest.xml 文件中声明网络权限,以便应用程序能够访问网络。添加以下代码:
```
<uses-permission android:name="android.permission.INTERNET" />
```
阅读全文