Instant Messaging Development Based on Rongyun (1)

I. Overview

In today's applications, the instant messaging function is very common. Starting from this article, we will study how to develop a software with instant messaging function based on the services of the third-party platform Rongyun.

First, enter the official website of Rongyun, the address is as follows:
http://rongcloud.cn/

write picture description here

Then we click login. If you don't have an account, you need to register first. After logging in successfully, you will enter the console page, and we will create an application.

write picture description here

We click on the application name on the left, and after entering, we can see some application details, such as AppKey

write picture description here

Then we click the download SDK on the right, and we will jump to the SDK download page.
write picture description here

Because we are developing based on the Android platform, we choose the Android SDK on the far left to download, and we can also download the Demo source code. The following introduces the difference between IMIKit and IMLib:

IM Interface Components - IMKit
IMKit is one of the core features of Rongyun SDK. Rongyun encapsulates the most complex session list, chat window, message content display, session setting and other functions in instant messaging products into components. With a short code, you can directly integrate the above interface into your App product, saving A lot of development and debugging time. Rongyun also supports the most abundant custom interface component functions in the industry, and you can freely design and develop it according to your own interface requirements.

The core class of IMKit is RongIM on the Android platform and RCIM on the iOS platform. These two classes represent the same meaning as IMKit in future development.

IM Communication Capability Library - IMLib
IMLib is a basic IM communication capability library without interface, which encapsulates communication capabilities and objects such as sessions and messages. After referring to the App project, developers need to implement the UI interface by themselves, which is relatively lightweight and suitable for developers who have high customization requirements for UI

The core class of IMLib is RongIMClient on Android platform and RCIMClient on iOS platform. These two classes represent the same meaning as IMLib in future development.

We download both things for later use

2. Construction of the environment

First, we create a new project in Android Studio, then import the IMKIT library of Rongyun, and associate it with our project. After the association is successful, we create a new global Application object, as follows

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        /**
         * OnCreate 会被多个进程重入,这段保护代码,确保只有您需要使用 RongIM 的进程和 Push 进程执行了 init。
         * io.rong.push 为融云 push 进程名称,不可修改。
         */
        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext())) ||
                "io.rong.push".equals(getCurProcessName(getApplicationContext()))) {

            /**
             * IMKit SDK调用第一步 初始化
             */
            RongIM.init(this);
        }
    }
    /**
     * 获得当前进程的名字
     *
     * @param context
     * @return 进程号
     */
    public static String getCurProcessName(Context context) {

        int pid = android.os.Process.myPid();

        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {

            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }
}

At the same time, configure our App object in the manifest file, as well as the applied Api Key

  <application
        android:name=".ui.App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="RONG_CLOUD_APP_KEY"
            android:value="pvxdm17jxjqpr" />

Then, we get the token, because we can't deploy the server program, so we can't get the token from the Rongyun server. Rongyun also provides us with an API debugging tool. You can enter the userid to get the token, as shown in the following figure

write picture description here

Enter the userid to get the token. We enter 10086 and 10010 respectively to get two tokens, which are used to connect to the server later.

The last step is to use the obtained token to connect to the server

  if (getApplicationInfo().packageName.equals(App.getCurProcessName(getApplicationContext()))) {
            RongIM.connect(token1, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {
                }
                @Override
                public void onSuccess(String userid) {
                    //userid,是我们在申请token时填入的userid
                    System.out.println("========userid" + userid);
                }
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                }
            });
        }

If the connection is successful, the userid when we apply for the token will be printed out. After testing, the userid is printed out correctly, indicating that we have successfully connected to the server.

The above is the most basic environment to build, and then we implement other functions.

3. Realization of avatar/nickname

To display the avatar, we need to set the user information provider, otherwise only the default avatar will be displayed in the chat interface.

Rongyun provides two ways to display the user's nickname and avatar from the data source of the App. Note that one way is sufficient when using it, and cannot be mixed.
1. Set user information provider
2. Use messages to carry user information

Here are the avatars of the two users

Trunks, 10086

write picture description here

Sun Wutian, 10010

write picture description here

Then introduce a function to refresh user information. If you need to, you can follow the following methods:

  RongIM.getInstance().refreshUserInfoCache(new UserInfo(mUserid.equals("10086")?"10086":"10010",
                        mUserid.equals("10086")?"我曾经是是特兰克斯":"我曾经是孙悟天",
                        mUserid.equals("10086")?Uri.parse(Constant.imageUrl3):Uri.parse(Constant.imageUrl4)));

4. Session list and session page

Next, we will integrate the session list and session page. I will not post the specific code. At the end of the article, I will give the download address of the Demo. Here I will show you the renderings after the integration.

Conversation List
By default, the content of the conversation list is empty, because we have not sent any messages at this time.

write picture description here

Next, we integrate the session interface. After the success, the rendering is as follows

write picture description here

We simulate clicking on a friend to enter the conversation interface and send a message. At this time, when we look back at the conversation list interface, we can see the message just sent.

write picture description here

Finally, we start two simulators and send messages to each other to test,

write picture description here

The message can be sent normally, indicating that our configuration is correct

Five. Session list parameter configuration modification

After implementing the basic functions, we will make some beautification and modification to the interface.

First of all, on the conversation page we want to show who is currently chatting with

The modified page is as follows, is it more beautiful than before?

write picture description here

The layout file of the session page is given below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.rongcloudim.ui.ConversationActivity">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/blue"
        >
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:textSize="20sp"
            android:layout_centerInParent="true"
            />
    </RelativeLayout>
    <fragment
        android:id="@+id/rc_conversation_content"
        android:name="io.rong.imkit.fragment.ConversationFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        />
</LinearLayout>

Note: The above fragment is the fragment that comes with Rongyun. We refer to it here. At the same time, we need to pay attention to adding an id or tag to this fragment, otherwise an error will be reported when running.

6. Voice and video call function integration

To integrate the voice or call function, we need to download the CallKit SDK,

write picture description here

After downloading, it depends on the project, and the IMKit component is no longer needed at this time, because CallKit is based on the IMKit component.

Since the voice and video functions of Rongyun need to be developed by certified companies or can be used after recharging, they will not be introduced in detail here.

Finally, give the Demo download address

Click here to download the source code

Guess you like

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