rongcloud_im_plugin 0.9.7+2

融云 IM Flutter plugin #

本文档讲解了如何使用 IM 的 Flutter Plugin,基于融云 iOS/Android 平台的 IMLib SDK

Flutter 官网

融云 iOS 文档集成

融云 Android 文档集成

源码地址 Github,任何问题可以通过 Github Issues 提问

前期准备 #

融云官网 申请开发者账号

通过管理后台的 "基本信息"->"App Key" 获取 AppKey

通过管理后台的 "IM 服务"—>"API 调用"->"用户服务"->"获取 Token",通过用户 id 获取 IMToken

依赖 IM Flutter plugin #

在项目的 pubspec.yaml 中写如下依赖

dependencies:
  flutter:
    sdk: flutter

  rongcloud_im_plugin: ^0.9.7+2

然后在项目路径执行 flutter packages get 来下载 Flutter Plugin

集成步骤 #

1.初始化 SDK #

RongcloudImPlugin.init(RongAppKey);

2.连接 IM #

int rc = await RongcloudImPlugin.connect(RongIMToken);
print('connect result');
print(rc);

API 调用 #

断开 IM 连接 #

//needPush 断开连接之后是否需要远程推送
RongcloudImPlugin.disconnect(bool needPush)

发送消息 #

发送文本消息

onSendMessage() async{
      TextMessage txtMessage = new TextMessage();
      txtMessage.content = "这条消息来自 flutter";
      Message msg = await RongcloudImPlugin.sendMessage(RCConversationType.Private, privateUserId, txtMessage);
      print("send message start senderUserId = "+msg.senderUserId);
  }

发送图片消息

onSendImageMessage() async {
    ImageMessage imgMessage = new ImageMessage();
    imgMessage.localPath = "image/local/path.jpg";
    Message msg = await RongcloudImPlugin.sendMessage(RCConversationType.Private, privateUserId, imgMessage);
    print("send image message start senderUserId = "+msg.senderUserId);
  }

发送结果回调

//消息发送结果回调
    RongcloudImPlugin.onMessageSend = (int messageId,int status,int code) {
      print("send message messsageId:"+messageId.toString()+" status:"+status.toString()+" code:"+code.toString());
    };

媒体消息媒体文件上传进度

//媒体消息(图片/语音消息)上传媒体进度的回调
    RongcloudImPlugin.onUploadMediaProgress = (int messageId,int progress) {
      print("upload media messsageId:"+messageId.toString()+" progress:"+progress.toString());
    };

接收消息 #

//消息接收回调
    RongcloudImPlugin.onMessageReceived = (Message msg,int left) {
      print("receive message messsageId:"+msg.messageId.toString()+" left:"+left.toString());
    };

历史消息 #

获取本地历史消息

onGetHistoryMessages() async {
    List msgs = await RongcloudImPlugin.getHistoryMessage(RCConversationType.Private, privateUserId, 0, 10);
    print("get history message");
    for(Message m in msgs) {
      print("sentTime = "+m.sentTime.toString());
    }
  }

获取远端历史消息

RongcloudImPlugin.getRemoteHistoryMessages(1, "1001", 0, 20,(List<Message> msgList,int code) {
      if(code == 0) {
        for(Message msg in msgList) {
          print("getRemoteHistoryMessages  success "+ msg.messageId.toString());
        }
      }else {
        print("getRemoteHistoryMessages error "+code.toString());
      }
    });

插入发出的消息

RongcloudImPlugin.insertOutgoingMessage(RCConversationType.Private, "1001", 10, msgT, 0, (msg,code){
      print("insertOutgoingMessage " + msg.content.encode() + " code " + code.toString());

    });

插入收到的消息

RongcloudImPlugin.insertIncomingMessage(RCConversationType.Private, "1002", "1002", 1, msgT , 0, (msg,code){
      print("insertIncomingMessage " + msg.content.encode() + " code " + code.toString());
    });

删除特定会话消息

RongcloudImPlugin.deleteMessages(RCConversationType.Private, "2002", (int code) {

});

批量删除消息

List<int> mids =  new List();
mids.add(1);
RongcloudImPlugin.deleteMessageByIds(mids, (int code) {

});

未读数 #

获取特定会话的未读数

RongcloudImPlugin.getUnreadCount(RCConversationType.Private, "targetId", (int count,int code) {
      if( 0 == code) {
        print("未读数为"+count.toString());
      }
    });

获取特定会话类型的未读数

RongcloudImPlugin.getUnreadCountConversationTypeList([RCConversationType.Private,RCConversationType.Group], true, (int count, int code) {
      if( 0 == code) {
        print("未读数为"+count.toString());
      }
    });

获取所有未读数

RongcloudImPlugin.getTotalUnreadCount((int count, int code) {
      if( 0 == code) {
        print("未读数为"+count.toString());
      }
    });

会话列表 #

获取会话列表

onGetConversationList() async {
    List conversationList = await RongcloudImPlugin.getConversationList([RCConversationType.Private,RCConversationType.Group,RCConversationType.System]);

    for(Conversation con in cons) {
      print("conversation latestMessageId " + con.latestMessageId.toString());
    }
  }

删除指定会话

RongcloudImPlugin.removeConversation(RCConversationType.Private, "1001", (success) {
      if(success) {
        print("删除会话成功");
      }
    });

黑名单 #

把用户加入黑名单

RongcloudImPlugin.addToBlackList(blackUserId, (int code) {
      print("_addBlackList:" + blackUserId + " code:" + code.toString());
    });

把用户移除黑名单

RongcloudImPlugin.removeFromBlackList(blackUserId, (int code) {
      print("_removeBalckList:" + blackUserId + " code:" + code.toString());
    });

查询特定用户的黑名单状态

RongcloudImPlugin.getBlackListStatus(blackUserId,
        (int blackStatus, int code) {
      if (0 == code) {
        if (RCBlackListStatus.In == blackStatus) {
          print("用户:" + blackUserId + " 在黑名单中");
        } else {
          print("用户:" + blackUserId + " 不在黑名单中");
        }
      } else {
        print("用户:" + blackUserId + " 黑名单状态查询失败" + code.toString());
      }
    });

查询已经设置的黑名单列表

RongcloudImPlugin.getBlackList((List/*<String>*/ userIdList, int code) {
      print("_getBlackList:" + userIdList.toString() + " code:" + code.toString());
      userIdList.forEach((userId) {
        print("userId:"+userId);
      });
    });

加入聊天室 #

onJoinChatRoom() {
    RongcloudImPlugin.joinChatRoom("testchatroomId", 10);
  }

加入聊天室回调

//加入聊天室结果回调
    RongcloudImPlugin.onJoinChatRoom = (String targetId,int status) {
      print("join chatroom:"+targetId+" status:"+status.toString());
    };

退出聊天室 #

onQuitChatRoom() {
    RongcloudImPlugin.quitChatRoom("testchatroomId");
  }

退出聊天室回调

//退出聊天室结果回调
    RongcloudImPlugin.onQuitChatRoom = (String targetId,int status) {
      print("quit chatroom:"+targetId+" status:"+status.toString());
    };

获取聊天室信息 #

onGetChatRoomInfo() async {
    ChatRoomInfo chatRoomInfo = await RongcloudImPlugin.getChatRoomInfo("testchatroomId", 10, RCChatRoomMemberOrder.Desc);
    print("onGetChatRoomInfo targetId ="+chatRoomInfo.targetId);
  }

Native 向 Flutter 传递数据 #

iOS 端传递数据:

[[RCIMFlutterWrapper sharedWrapper] sendDataToFlutter:@{@"key":@"ios"}];

Android 端传递数据:

Map map = new HashMap();
map.put("key","android");
RCIMFlutterWrapper.getInstance().sendDataToFlutter(map);

Flutter 端接收数据:

RongcloudImPlugin.onDataReceived = (Map map) {
  print("object onDataReceived " + map.toString());
};

更多接口请参考

常见问题

0.9.7+2 #

  • SDK:
  • 1.修复设置会话免打扰状态接口的错误

0.9.7+1 #

  • SDK:
  • 1.修复获取会话免打扰状态的错误
  • 2.增加消息免打扰的枚举值

0.9.7 #

0.9.6 #

  • SDK:
  • 1.增加发送消息接口,消息可以发送 pushContent 和 pushData
  • 2.iOS/Android 增加接口,可以向 Flutter 传递数据

0.9.5 #

  • SDK:

  • 1.增加错误码

  • 2.解决发送图片,语音消息 extra 字段无效的问题

  • 3.解决 Android 发送图片没有缩略图的问题

  • 4.增加黑名单相关接口

  • 5.更新文档

  • Demo:

  • 1.增加会话长按和消息长按功能

  • 2.增加点击消息用户头像回调

  • 3.实现本地通知功能

  • 4.更新文档

0.9.4 #

  • 解决 Android 时间戳 Long 强转为 Integer 报错 详细参见

0.9.3 #

  • 增加删除历史消息的接口:删除特定会话消息;批量删除消息
  • 修复 Android getRemoteHistoryMessages 接口 recordTime 类型出错

0.9.2 #

  • 解决 Android 非法 token 连接报非主线程执行的问题

0.9.1 #

  • 获取会话列表接口改为按照回话类型获取
  • 解决部分接口的 null exception

0.9.0 #

  • 新增接口:插入收到的消息,插入发出的消息,获取所有未读,获取单个会话未读,获取指定会话类型的未读,删除会话,连接状态回调,免打扰接口,置顶会话

  • 变更接口:将所有的 iOS、Android 的回调从 handler 中移除,改为通过 Function 返回 ,如接受消息的回调改为下面的方式,具体可以参见 RongcloudImPlugin

//消息接收回调
    RongcloudImPlugin.onMessageReceived = (Message msg,int left) {
      print("receive message messsageId:"+msg.messageId.toString()+" left:"+left.toString());
    };

0.0.22 #

  • 解决 iOS 清空未读数失败的问题

0.0.21 #

  • 解决 Android 接收消息在非 UI 线程通过 MethodChannel 返回数据导致的 java.lang.RuntimeException: Methods marked with @UiThread must be executed on the main thread. Current thread: Binder:9497_1

0.0.20 #

  • 解决 iOS connect 成功返回 null 的问题

0.0.19 #

  • 增加消息发送结果的错误码

0.0.18 #

  • 新增语音消息

0.0.17 #

  • 更新 readme 文档

0.0.16 #

  • 更新 readme 文档;sendMessage 接口由返回 map,改为返回 Message

0.0.15 #

  • 删除 style.xml 中问题注释,保证 android 编译

0.0.14 #

  • 注掉 release 模式无法被找到的 theme

0.0.13 #

  • 删除 android 配置文件依赖的错误 theme : release 模式找不到这个 theme

0.0.12 #

  • dart 获取会话列表,消息列表的非法数据问题;增加 system 会话类型

0.0.11 #

  • 增加清除特定回话未读数的接口;解决 android 获取空会话列表的空指针问题

0.0.10 #

  • 图片消息解析;获取聊天室信息

0.0.9 #

  • 更新 iOS 为 static framework

0.0.8 #

  • 增加获取会话列表的接口;修复安卓获取消息的 conversationType 为 null 的问题

0.0.7 #

  • demo 中增加自定义消息的处理;增加获取特定回话消息列表接口

0.0.6 #

  • Android 临时去掉会话列表和聊天页面

0.0.5 #

  • 增加图片消息,增加聊天室加入/退出接口

0.0.4 #

  • 解决收 Android 消息异常的问题

0.0.3 #

  • 增加消息收发接口

0.0.2 #

  • 更新开发文档

0.0.1 #

  • 实现 初始化、配置、连接 IM、进入会话列表、进入会话页面、刷新用户信息等功能

example/README.md

融云 IM Flutter Plugin Demo #

iOS 初次运行 #

初次安装需要从 pod 下载 IMLib 的 iOS SDK,要花费较长的时间,建议手动更新一下

  1. Podfile 目录执行 pod repo update 命令
  2. Podfile 目录执行 pod update 命令

常见问题 #

  1. audio_recorder does not specify a Swift version and none of the targets (Runner) integrating it have the SWIFT_VERSION attribute set. Please contact the author or set the SWIFT_VERSION attribute in at least one of the targets that integrate this pod.

Podfile 上添加 use_frameworks! 参数

Xcode 打开,选择 TARGETS -> Runnder -> Build Settings -> Levels 右边加号 -> Add User-Defined Setting -> 添加字段 SWIFT_VERSION,写上 Swift 版本,如 4.0

Android 初次运行 #

Android 依赖不同的 Flutter Plugin 可能会出现不同版本的 Gradle 导致编译不通过,可以按需做如下处理

  1. 将所有的 build.gradle 的 gradle 版本统一,例如统一改为 3.4.1
  2. 将 gradle-wrapper.properties 的 distributionUrl版本改为和上一步统一,如上一步是 3.4.1 ,那么此处应该改为 5.1.1
  3. 编译后查看是否存在 AndroidX 的冲突,如果存在 AndroidX 冲突,那么在 gradle.properties 增加如下配置
android.useAndroidX=true
android.enableJetifier=true

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  rongcloud_im_plugin: ^0.9.7+2

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
74
Health:
Code health derived from static analysis. [more]
99
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
83
Learn more about scoring.

We analyzed this package on Sep 20, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.5.0
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.2

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Fix lib/src/message_content.dart. (-0.50 points)

Analysis of lib/src/message_content.dart reported 1 hint:

line 1 col 8: Unused import: 'common_define.dart'.

Fix lib/src/message_factory.dart. (-0.50 points)

Analysis of lib/src/message_factory.dart reported 1 hint:

line 118 col 20: Don't explicitly initialize variables to null.

Format lib/rongcloud_im_plugin.dart.

Run flutter format to format lib/rongcloud_im_plugin.dart.

Fix additional 10 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/src/chatroom_info.dart (Run flutter format to format lib/src/chatroom_info.dart.)
  • lib/src/common_define.dart (Run flutter format to format lib/src/common_define.dart.)
  • lib/src/connection_status_convert.dart (Run flutter format to format lib/src/connection_status_convert.dart.)
  • lib/src/conversation.dart (Run flutter format to format lib/src/conversation.dart.)
  • lib/src/image_message.dart (Run flutter format to format lib/src/image_message.dart.)
  • lib/src/message.dart (Run flutter format to format lib/src/message.dart.)
  • lib/src/method_key.dart (Run flutter format to format lib/src/method_key.dart.)
  • lib/src/rong_im_plugin.dart (Run flutter format to format lib/src/rong_im_plugin.dart.)
  • lib/src/text_message.dart (Run flutter format to format lib/src/text_message.dart.)
  • lib/src/voice_message.dart (Run flutter format to format lib/src/voice_message.dart.)

Maintenance suggestions

The package description is too short. (-20 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.7
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test