Android 两个手机通过 WiFi 传输图片的实现教程

在当今移动设备普及的时代,手机之间的文件传输变得越来越重要。本文将帮助你实现两部Android手机之间通过WiFi直接传输图片的功能。我们将分步骤讲解整个流程,并提供源代码示例,这样即使是刚入行的小白也能轻松上手。

流程概览

在开始之前,我们需要了解一下整个流程。我们可以将过程分为以下几个步骤:

步骤 操作描述
步骤 1 在发送方设备上选择图片
步骤 2 建立两部设备之间的WiFi连接
步骤 3 发送方将图片数据打包并发送
步骤 4 接收方解包数据并保存图片
步骤 5 显示接收到的图片

关系图

接下来,我们可以通过关系图来对整个系统的组件进行可视化。

erDiagram
    USER {
        string name
    }
    IMAGE {
        string filePath
        string fileName
    }
    USER ||--o{ IMAGE : sends

具体实现步骤

步骤 1:在发送方设备上选择图片

用户通过设备的图库选择图片。可以使用Android的Intent来打开图库。

// 打开图库选择图片
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE);

步骤 2:建立两部设备之间的WiFi连接

实现局域网连接,通常是通过配置一个WiFi热点和socket通信实现的。以下是如何设置WiFi热点。

// 创建WiFi热点
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "MyHotspot"; // 热点名称
wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); // 不设密码
wifiManager.setWifiEnabled(false); // 先关闭WiFi
wifiManager.addNetwork(wifiConfig);
wifiManager.saveConfiguration();

步骤 3:发送方将图片数据打包并发送

发送图片数据需要使用Socket进行网络通信。以下是发送图片的实现。

// 使用Socket发送数据
Socket socket = new Socket(serverIP, serverPort); // 指定接收方的IP和端口
OutputStream outputStream = socket.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(filePath); // 从文件路径读取图片
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
fileInputStream.close();
socket.close();

步骤 4:接收方解包数据并保存图片

接收方需要创建一个Socket并接收图片数据。

// 使用Socket接收数据
ServerSocket serverSocket = new ServerSocket(serverPort);
Socket clientSocket = serverSocket.accept(); // 阻塞,等待连接
InputStream inputStream = clientSocket.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(savePath); // 指定保存的文件路径
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
    fileOutputStream.write(buffer, 0, bytesRead); // 将接收到的数据写入文件
}
inputStream.close();
fileOutputStream.close();
clientSocket.close();
serverSocket.close();

步骤 5:显示接收到的图片

最后,接收方可以使用ImageView展示接收到的图片。

// 显示接收到的图片
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Bitmap bitmap = BitmapFactory.decodeFile(savePath); // 从文件路径解码图片
imageView.setImageBitmap(bitmap); // 设置ImageView显示图片

序列图

我们可以通过序列图来展示发送方和接收方之间的交互过程。

sequenceDiagram
    participant Sender
    participant Receiver
    Sender->>Receiver: Establish WiFi connection
    Sender->>Sender: Select Image
    Sender->>Sender: Send Image via Socket
    Receiver->>Receiver: Receive Image via Socket
    Receiver->>Receiver: Display Image

结尾

通过以上步骤和代码示例,你应该能够实现两部Android手机之间的WiFi图片传输。整个过程涉及用户界面交互、网络通信和文件操作等多个方面。希望这篇文章对你有所帮助,如果有任何问题,欢迎随时向我提问!