Rongyun RongIMKit instant messaging development (let's chat)

1 Introduction

Now that there are more and more APP functions, chat has become a very important function. Now the popular instant messaging SDKs on the market are basically only Rongyun and Huanxin. In recent years, Rongyun has a trend of surpassing Huanxin in all aspects, so There are more and more places where Rongyun is used in projects. So, should we also introduce the realization of Rongyun?

RongIM instant messaging is divided into two parts.. One is KIT and the other is LIB.. Kit belongs to the SDK with a higher degree of encapsulation.. The session interface list has been fully implemented.. It is easy to call but has low customization... Suitable for junior and intermediate programmers (such as I) and small and medium-sized companies to develop efficiently and quickly.. Lib is a SDK with a very low degree of packaging.. The list interface needs to be implemented by itself.. Suitable for middle and senior programmers (my fathers) and medium and large companies. Elaborately crafted.. This article mainly introduces the implementation of Android RongIMKit... If fathers want to understand the implementation of Lib, I can only say...

(Pfft) My son knelt down for you... Do you still accept your son...

2. Basic implementation

The front is pure bullshit... Let's get to the point..

The implementation of RongIMKit is actually very simple. Kit is mainly divided into three modules, namely the session list (io.rong.imkit.fragment.ConversationListFragment), the aggregated session list (io.rong.imkit.fragment.SubConversationListFragment) and the session interface (io. rong.fast.activity.ConversationActivity) .. The conversation list is the message interface.. The feature of Rongyun is that it only maintains the chat list.. But he doesn't care about friendship... This is embarrassing.. (How to deal with it will be described in detail later) So the friend list Rongyun dad doesn't care.. We only need to integrate these three interfaces and then use Rongyun to open the interface code

//启动会话界面
if (RongIM.getInstance() != null)
                    RongIM.getInstance().startPrivateChat(this, "26594", "title");

//启动会话列表界面
if (RongIM.getInstance() != null)
                   RongIM.getInstance().startConversationList(this);

//启动聚合会话列表界面
if (RongIM.getInstance() != null)
                   RongIM.getInstance().startSubConversationList(this, Conversation.ConversationType.GROUP);

Just go to the interface.. See the process of quick integration

Rongyun rapid integration

Okay, this is the end of this article... Let's go and see the documentation ╮(╯▽╰)╭... Thanks for the official documentation of Rongyun... Goodbye... Hey, hey, don't be sore...

What I'm actually trying to say is... It's important to note that..

2.1. Intent selector

The official let us configure in the manifest such as

    <activity
    android:name="io.rong.fast.activity.ConversationListActivity"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateHidden|adjustResize">

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />

        <data
            android:host="io.rong.fast"
            android:pathPrefix="/conversationlist"
            android:scheme="rong" />
    </intent-filter>
</activity>

The intent selector of .. actually has two functions... One is when a push is received.. Click the notification bar to enter the interface for configuring the intent selector.. (For example, if you receive a message from a person.. Click the notification bar to Enter the single chat interface.. If you receive multiple messages from multiple people.. Click to enter the conversation list interface) And this interface may not only have fragments of Rongyun, such as the interface of my APP

write picture description here

Then when entering this interface, you must configure the intent selector in the interface manifast and call it

RongIM.getInstance().startConversationList(this);

to enter the interface.. Otherwise, the initialization of the interface will be unsuccessful...

And the list itself is actually just a fragment.. just press

<fragment
        android:id="@+id/conversationlist"
        android:name="io.rong.imkit.fragment.ConversationListFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

It is possible to refer to or dynamically refer to.. See details

fragment reference

2.2. The difference between the aggregated session list and the session list

SubConversationList actually means sub-conversation list in English. In fact, it is a sub-list down the conversation list. For example, in QQ.. There is a group list system message list, etc... You can enter after clicking on the conversation list Another list is the aggregated session list.. In Rongyun, group chat messages will be displayed in the aggregated session list... and system messages will also be displayed.. As for whether to push or not to push system messages, the server handles it.. If the server does not There is no push system message... So this interface does not have to be integrated.. If you don't have a group and no system message.. If you are only chatting.. This interface may not be implemented...

At this point, the interface of Rongyun is basically completed... If you think this is the end? Pattern=.=

3. Rongyun realizes details processing

The previous article also mentioned that Rongyun's father does not maintain friendship... This is very embarrassing... You don't know how we are friends and chat... Can strangers chat? How can you put my avatar without user information? The name is posted... There are more of these problems.. I need to start from the ancient times.. Once upon a time there was a mountain.. There was a temple in the mountain... The temple lived... Hey, don't fight, don't fight, hurt, hurt... .

3.1. Content Providers

Rongyun's avatar and name need to be provided by the content provider to Rongyun for local use by the user. Note that it is local.. That is to say, the image name is only displayed locally for you. You need to call it at the right time.

RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
      @Override
      public UserInfo getUserInfo(String s) {
            for (int i = 0; i < friendList.size(); i++) {
               return findUserInfo();
                                    }
                                }, true); // 提供一群人信息

RongIM.getInstance().refreshUserInfoCache(new UserInfo(friendList.get(i).userId + "", friendList.get(i).nickname + "", Uri.parse(friendList.get(i).avatar))); // 提供一个人信息

In the find method, find the user information and pass it to userinfo.. After instantiation, return.. Such as...

for (int i = 0; i < friendList.size(); i++) {
        if ((friendList.get(i).userId + "").equals(s)) {
           return new UserInfo(friendList.get(i).userId + "",
            friendList.get(i).nickname + "", Uri.parse(friendList.get(i).avatar));
                                            }
                                        }

Find the information and provide it.. In this way, Rongyun can correctly match and display the avatar and nickname according to the ID. It should be noted that the nickname of your own avatar should also be provided... Otherwise, you are the default avatar... So you need to use refreshUserInfoCache to provide your own information. Up, refreshUserInfoCache can also refresh the information of a certain ID in the content provider... Realize a single change
Group also has a group provider

RongIM.setGroupInfoProvider(new RongIM.GroupInfoProvider() {

     @Override
     public Group getGroupInfo(String s) {
              int result = 0;

              for (int i = 0; i < groupList.size(); i++) {
                      if (s.equals(groupList.get(i).id + ""))
                           result = i;
                                    }

             return new Group(groupList.get(result).id + "",

              groupList.get(result).name, Uri.parse(groupList.get(result).picture));

              }
 }, true); //提供一群群组信息

RongIM.getInstance().refreshGroupInfoCache(new Group(groupList.get(i).id + "", groupList.get(i).name, Uri.parse(groupList.get(i).picture))); // 添加一个群组信息

This way you can see other people's avatars.. (Although other people's avatars still require me to provide a bit weird = =;)

3.2. The synchronization list is consistent with the friend relationship

In the end... We are still struggling with Rongyun's unsynchronized friend relationship.. Because Rongyun does not save our friend relationship.. So we have to find a way to synchronize our friend relationship when using Rongyun.. You deleted and blocked or kicked you out of the group... That person still remains in the message list.. And because Rongyun doesn't know that you are blocked... So the chat can still be successful... This is very embarrassing. .

So for this situation... when you delete the friend relationship of the other party or when you leave the group.. to call

RongIM.getInstance().removeConversation(Conversation.ConversationType.PRIVATE, userId);//个人

RongIM.getInstance().removeConversation(Conversation.ConversationType.GROUP, targetGroupId);群组

To remove the chat relationship that exists in the conversation list..

The deleted party needs to synchronize in real time through push.. (For example, Jiguang pushes custom messages... pass the deleted ID..)

And every time you go online.. you can pass

RongIM.getInstance().getConversationList(Conversation.ConversationType.PRIVATE)//个人

RongIM.getInstance().getConversationList(Conversation.ConversationType.GROUP)//群组

Go to get the individuals and groups that exist in the conversation list... Then get the Conversation object of this list.. Call getTargetId() to get the ID... Then compare it with the friend list and group ID list obtained from the server to delete...

It should be noted here that although the method of RongIM.getInstance().getConversationList(type) can get the information in the session list, these messages do not necessarily belong to your own account.
For example,
you Chat with the account with ID 1. The cached information of the chat record is left in the conversation list.. But you log in with the account with ID 2. Call the RongIM.getInstance().getConversationList(type) method but you can still get it Go to the record in the session list of 1. If we simply compare the list with our own friend relationship.. Maybe we will delete the session record of 1 on 2. Then switch back to 1 and log in and find it is empty...
So The solution is.. When deleting, you have to make a judgment between conversation.getSenderUserId() and your own ID.. You cannot delete the information in other accounts...

This ensures that the list and friend relationship remain consistent...

4. Finally, some commonly used APIs or methods are introduced

4.1. Withdrawing a message

Recalling a message is a commonly used function in chat.. But it is turned off by default... It needs to be configured in res-values ​​- rc_config.xml in the SDK.. If there is a comment in it, just find it and change it to true...=.=

write picture description here

4.2. Muting messages

This feature is often used too..

is called

RongIM.getInstance().setConversationNotificationStatus(
       Conversation.ConversationType.GROUP,//群聊或单聊
       id,//群ID或单聊ID
        Conversation.ConversationNotificationStatus.DO_NOT_DISTURB,//静音..打开改为NOTIFY即可
       new RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() { //设置成功后的回调
           @Override
           public void onSuccess(Conversation.ConversationNotificationStatus conversationNotificationStatus) {
                                                     }

           @Override
           public void onError(RongIMClient.ErrorCode errorCode) {

                                                     }
                                                 }

                                         );

Do not disturb

4.3. Receive push

The official description is...
After version 2.6.0, our notification display mechanism has changed, and you need to customize a broadcast receiver that inherits PushMessageReceiver (must be implemented, otherwise it may cause click on the background notification to not respond, or not receive Push notifications, etc.), please refer to the documentation for details.

Asi... Which software is sent by someone else and you don't give it a push... You have to ask the developer to implement the broadcast receiver by himself. What is it that is not sick = = ;

In short, just write a broadcast receiver and configure it in the manifest. For details, see
How to use push

It should be noted here that you must integrate Huawei and Xiaomi push.. Huawei and Xiaomi will kill the background.. If you don’t integrate Xiaomi Huawei.. Your push will only last five minutes.. As for the integration process, it is already detailed in the official documents above. .. Xiaomi push is newer than the document.. If you want to use the new version of Xiaomi push to catch up with the trend, you need to set the manifest according to the process of Xiaomi official website.. And I don’t know if Rongyun is compatible.. So it is best to use Rongyun The Xiaomi push.jar in the official cloud demo Hi Leopard can be integrated..

The pit of Huawei push is incompatible with Baidu map. Because Huawei push is an SDK that integrates the positioning function of Baidu map to realize the geographical reporting function. If your project itself has integrated Baidu map.. This will blow up your sakalaka when compiling.. The solution is to ask your product manager not to use Baidu map for Gaode =.=.. That is impossible..

In fact, Baidu
can
find the answer in Huawei push jar package conflict here... You can use the decompression tool to open the jar package.. Then delete the jar package related to Baidu map. Then enter the assert directory and delete all the pictures. . In fact, there is no problem without deleting the picture.. It will only increase the size of your APP... So it is best to delete it..

It's basically no problem to push

4.4. Reconnect

Because Rongyun instant messaging needs to keep connected... If the APP is in the background for a long time.. it will be... hey hey... you wake up, Yunyun.. you don't want to die... So it is recommended to do it in the life cycle resume() of the chat list interface. Reconnection..


  @Override
    public void onResume() {
        if (RongIM.getInstance().getCurrentConnectionStatus() != RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED ) { //如果不是连接状态则重连
            reconnect(SharedPrefUtil.getString(getActivity(),Constants.KEY_RONGCLOUD_TOKEN,""));

        }
        super.onResume();
    }







    /**
     * 重连
     *
     * @param token
     */
    private void reconnect(String token) {

        if (getActivity().getApplicationInfo().packageName.equals(App.getCurProcessName(getActivity().getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {

                }

                @Override
                public void onSuccess(String s) {

                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            });
        }
    }

This will ensure that it works properly every time you enter the list.

4.5. A little trick - use Rongyun to kick people offline

Because Rongyun itself only allows one person to be online.. It does not allow multiple terminals with the same ID to be online at the same time.. So there will be a situation of kicking off the line.. We can use this monitoring.. to realize the kick-off function of our entire APP...

monitor link status



RongIM.setConnectionStatusListener(new RongIMClient.ConnectionStatusListener() {
            @Override
            public void onChanged(ConnectionStatus connectionStatus) {
                if (connectionStatus == ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT) {
                    EventBus.getDefault().post(new ExitEvent()); // 利用eventbus结束掉所有界面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(getApplicationContext(),"你的账号在别处登录,您被迫下线");
                        }
                    });
                    startActivity(new Intent(getApplicationContext(), DirectlyLoginActivity.class)); //重新回到登录界面
                }
            }


        });

This is how I implemented it.. of course there can be a better implementation.. if you have...

(Pfft) Dad and son knelt down for you... You secretly message me to teach my son...

4.6. Optimize the list long press dialog

Because dialog Rongyun uses the native effect by default, which may not match the style of the app. So we may need to customize the dialog. How to get rid of the original ugly dialog. First, you have to
use RongIM.setConversationListBehaviorListener() RongIM.setConversationBehaviorListener() Change the long press operation to true.. Play your own dialog.. Then call the corresponding api for the click event.. Let me tell you all the APIs I use..

Conversation interface message long press RongIM.setConversationBehaviorListener() onMessageLongClick

Where message is a parameter passed in the onMessageLongClick method.. You can pass it into the dialog constructor..
Copy the message

ClipboardManager clipboard = (ClipboardManager) view.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setText(((TextMessage) message.getContent()).getContent());

delete message

int[] i = new int[] {message.getMessageId()};
RongIM.getInstance().deleteMessages(i);

Withdraw message (note that calling the withdraw API directly here is not limited by the previous time.. )

RongIM.getInstance().recallMessage(message);

Then what needs to be dealt with is.. If message.getSenderUserId() is not my ID or it exceeds a certain period of time, it will not be withdrawn and displayed. If (message.getContent() instanceof TextMessage) is not true, that is to say, the message is not text.. It is voice or If the picture is.. then do not let the copy display..

if(!(message.getContent() instanceof TextMessage)) {
            RLMessageCopy.setVisibility(View.GONE);
        }
if (!message.getSenderUserId() .equals(SharedPrefUtil.getString(getContext(), Constants.USER_ID,"")) || System.currentTimeMillis() -message.getSentTime() > 120000) {
            RLMessageRecall.setVisibility(View.GONE);
        }

Conversation list interface message long press RongIM.setConversationListBehaviorListener() onConversationLongClick

Among them, uiConversation is the parameter passed from onConversationLongClick.. It can still be passed into the dialog using the construction method..
Top message

RongIM.getInstance().setConversationToTop(uiConversation.getConversationType(),uiConversation.getConversationTargetId(),true);

delete message

RongIM.getInstance().removeConversation(uiConversation.getConversationType(),uiConversation.getConversationTargetId());

This way you can do whatever you want with your dialog animation position style.. hehehe...

5. Summary

So far.. I have learned what I have learned all my life... ah no.. I have shared my experience in the past few days.. It is not difficult to use Rongyun.. It is mainly a lot of details that need to be dealt with... Every situation requires Go to synchronize the friend list and the message list.. If you are doing Rongyun for the first time.. You can take a closer look at my method above.. Encapsulate the tool class reuse every time you want to synchronize.. Otherwise It would be very hard to go back and change it later.

If you have any dissatisfaction with my article, please send me a private message... Anyway, I will ignore you... hum ╭(╯^╰)╮

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325483116&siteId=291194637