在Android中,可以使用Java的Socket類來進行網(wǎng)絡(luò)通信。以下是一個簡單的封裝方法示例:
1、創(chuàng)建一個SocketClient類:
```java
public class SocketClient {
private Socket socket;
private BufferedReader reader;
private BufferedWriter writer;
public SocketClient() {
try {
// 創(chuàng)建Socket對象
socket = new Socket("服務(wù)器IP地址", 服務(wù)器端口號);
// 創(chuàng)建輸入輸出流
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public String sendMessage(String message) {
try {
// 發(fā)送消息
writer.write(message + "\n");
writer.flush();
// 接收服務(wù)器返回的消息
String response = reader.readLine();
return response;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void close() {
try {
// 關(guān)閉輸入輸出流和Socket連接
writer.close();
reader.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2、在需要使用Socket的地方創(chuàng)建一個SocketClient對象,并調(diào)用sendMessage方法發(fā)送消息并接收服務(wù)器返回的消息:
```java
SocketClient client = new SocketClient();
String response = client.sendMessage("要發(fā)送的消息");
client.close();
```
這是一個簡單的Socket封裝方法示例,具體的實現(xiàn)可能還需要根據(jù)實際需求進行修改和完善。