You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android Java中使用Agora SDK实现文件收发功能?

Agora SDK 集成文件附件功能实现示例

以下是基于Agora Chat(即时通讯)SDK实现文件附件发送与接收的代码示例,涵盖Android和iOS平台:

Android 平台实现

发送文件附件

// 1. 获取本地文件路径(示例为本地文档路径,实际可通过文件选择器获取)
String filePath = "/storage/emulated/0/Documents/test.pdf";
File targetFile = new File(filePath);

// 2. 创建文件发送消息
ChatMessage fileMsg = ChatMessage.createFileSendMessage("目标用户ID", targetFile, false);
// 可选:手动设置文件属性(SDK会自动获取,也可自定义)
fileMsg.setAttribute("file_name", targetFile.getName());
fileMsg.setAttribute("file_size", targetFile.length());

// 3. 发送文件消息
ChatClient.getInstance().chatManager().sendMessage(fileMsg, new CallBack() {
    @Override
    public void onSuccess() {
        // 发送成功,更新聊天界面或提示用户
        Log.d("AgoraChat", "文件消息发送成功");
    }

    @Override
    public void onError(int code, String errorMsg) {
        // 发送失败,处理错误逻辑
        Log.e("AgoraChat", "文件发送失败:" + errorMsg);
    }
});

接收文件附件

先注册消息监听器,再处理文件消息:

// 注册全局消息监听
ChatClient.getInstance().chatManager().addMessageListener(new MessageListener() {
    @Override
    public void onMessageReceived(List<ChatMessage> messages) {
        for (ChatMessage msg : messages) {
            // 判断是否为文件消息
            if (msg.getType() == ChatMessage.Type.FILE) {
                String fileName = msg.getFileName();
                long fileSize = msg.getFileSize();
                String remoteFileUrl = msg.getFileUrl();

                // 下载文件到本地
                ChatClient.getInstance().chatManager().downloadAttachment(msg, new DownloadAttachmentCallBack() {
                    @Override
                    public void onSuccess(String localFilePath) {
                        // 下载完成,可打开文件或更新UI
                        Log.d("AgoraChat", "文件下载完成,本地路径:" + localFilePath);
                    }

                    @Override
                    public void onError(int code, String errorMsg) {
                        Log.e("AgoraChat", "文件下载失败:" + errorMsg);
                    }

                    @Override
                    public void onProgress(int progress) {
                        // 实时更新下载进度
                        Log.d("AgoraChat", "下载进度:" + progress + "%");
                    }
                });
            }
        }
    }

    // 其他监听方法可按需实现
});

iOS 平台实现(Swift)

发送文件附件

// 1. 获取本地文件URL(示例从Bundle获取,实际可通过文件选择器获取)
guard let fileUrl = Bundle.main.url(forResource: "test", withExtension: "pdf") else {
    print("文件不存在")
    return
}
let receiverUserId = "目标用户ID"

// 2. 创建文件消息
AgoraChatClient.shared().chatManager?.createFileMessage(
    withTargetId: receiverUserId,
    fileUrl: fileUrl,
    displayName: fileUrl.lastPathComponent,
    completion: { message, error in
        guard let fileMessage = message, error == nil else {
            print("创建文件消息失败:\(error?.localizedDescription ?? "未知错误")")
            return
        }
        
        // 3. 发送文件消息,监听上传进度
        AgoraChatClient.shared().chatManager?.send(
            fileMessage,
            progress: { progress in
                print("文件上传进度:\(progress)%")
            },
            completion: { _, error in
                if let err = error {
                    print("文件发送失败:\(err.localizedDescription)")
                } else {
                    print("文件消息发送成功")
                }
            }
        )
    }
)

接收文件附件

实现AgoraChatManagerDelegate协议处理消息:

// 注册消息监听
AgoraChatClient.shared().chatManager?.add(self, delegateQueue: nil)

// 扩展实现代理方法
extension ChatViewController: AgoraChatManagerDelegate {
    func messagesDidReceive(_ aMessages: [AgoraChatMessage]) {
        for msg in aMessages {
            guard msg.type == .file else { continue }
            
            // 获取文件基本信息
            let fileName = msg.fileName ?? "未命名文件"
            let fileSize = msg.fileSize
            let remoteUrl = msg.remoteUrl
            
            // 下载文件
            AgoraChatClient.shared().chatManager?.downloadAttachment(
                msg,
                progress: { progress in
                    print("文件下载进度:\(progress)%")
                },
                completion: { localPath, error in
                    if let err = error {
                        print("文件下载失败:\(err.localizedDescription)")
                    } else if let path = localPath {
                        print("文件下载完成,本地路径:\(path)")
                        // 此处可添加打开文件的逻辑
                    }
                }
            )
        }
    }
}

关键注意事项

  • 需在Agora控制台开启文件存储服务,若使用第三方存储(如OSS、S3)需完成对应配置
  • 注意文件大小限制:Agora Chat默认限制文件大小,如需更大文件需在控制台调整参数
  • 权限处理:Android需申请文件读写权限;iOS需开启文件访问相关权限
  • 异常处理:需添加网络波动时的重试逻辑、文件不存在的容错处理

内容的提问来源于stack exchange,提问作者IT Student

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 00:57:29