Android 两台手机通过wifi热点通信
时间: 2023-09-14 20:06:00 浏览: 75
要实现两台Android手机之间的WiFi热点通信,可以使用Android提供的Socket API和WifiManager API。
以下是基本步骤:
1. 创建WiFi热点
在一个手机上打开WiFi热点。您可以通过使用WifiManager类中的setWifiApEnabled()方法来创建WiFi热点。例如:
```
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "MyWifiHotspot";
wifiConfig.preSharedKey = "password";
wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
Method setWifiApMethod = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
setWifiApMethod.invoke(wifiManager, wifiConfig, true);
```
2. 连接到WiFi热点
在另一个手机上连接到WiFi热点。您可以使用WifiManager类中的addNetwork()、enableNetwork()和reconnect()方法来连接到WiFi热点。例如:
```
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "MyWifiHotspot";
wifiConfig.preSharedKey = "password";
wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
int networkId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(networkId, true);
wifiManager.reconnect();
```
3. 创建Socket连接
使用Socket API在两个手机之间创建Socket连接。在一个手机上作为服务器,另一个手机作为客户端。例如:
在服务器端:
```
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
```
在客户端:
```
Socket socket = new Socket(serverIpAddress, 8888);
```
4. 通过Socket传输数据
在Socket连接建立后,可以使用输入流和输出流来传输数据。在服务器端和客户端都需要使用输入流和输出流。例如:
在服务器端:
```
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF("Hello from server");
dataOutputStream.flush();
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
String message = dataInputStream.readUTF();
```
在客户端:
```
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF("Hello from client");
dataOutputStream.flush();
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
String message = dataInputStream.readUTF();
```
以上就是Android两台手机之间通过WiFi热点通信的基本步骤。