IM combat: Android access Huanxin IM SDK

Objectives of this study:

  1. Register for Huanxin;
  2. The Android side integrates Huanxin IM SDK;
  3. Realize registration-login-send message-session list, etc.;

1. Huanxin IM

       What is Huanxin IM

Huanxin IM is an instant messaging product that provides developers with instant messaging capabilities based on the mobile Internet, such as single chat, group chat, voice, picture, location, etc., allowing developers to get rid of the heavy development of the bottom layer of mobile IM communication, and the app can have built-in IM capabilities within 24 hours .

      What can Huanxin IM achieve?

Realize the functions of sending messages, voices, pictures, and locations between individuals, groups, and chat rooms, and provide a set of EaseIMKit ui libraries for developers to use immediately;

2. The basic flow of Huanxin IM to realize communication

  1. Huanxin Account

88689e05e85e4717d5832bd5300c82b9.png

2. Connect the Android terminal to Huanxin SDK

Choose any of the following methods to integrate the Huanxin Instant Messaging IM SDK into your project (you only need to choose one of the following integration methods, and an error may be reported if you use multiple integration methods at the same time):

method one:

This method is only applicable to v3.8.2 or above.

1. Add the mavenCentral() repository in the project's build.gradle.

buildscript {
    repositories {
        ...
        mavenCentral()
    }
    ...
}

allprojects {
    repositories {
        ...
        mavenCentral()
    }
}

2. Add the following dependencies to the build.gradle of the module:

dependencies {
    ...
    // x.y.z 请填写具体版本号,如:3.9.4。
    // 可通过 SDK 发版说明获得最新版本号。
    implementation 'io.hyphenate:hyphenate-chat:x.x.x'
}

Method Two:

Manually copy the SDK files

Open the SDK download page, get the latest version of Huanxin Instant Messaging IM Android SDK, and then unzip it.

Copy the following files under the libs path in the SDK package to your project path:

3. Android registration and login

(1) Initialize in the main process:

EMOptions options = new EMOptions();
options.setAppKey("Your appkey");
......// 其他 EMOptions 配置。
EMClient.getInstance().init(context, options);

(2) Create an account

This method is a synchronous method that blocks the current thread;

This method can only be called in open registration mode. If this method reports an error, please check whether the Huanxin management background is in the open registration mode;

// 注册失败会抛出 HyphenateException。
// 同步方法,会阻塞当前线程。
EMClient.getInstance().createAccount(mAccount, mPassword);

(3) Login account

EMClient.getInstance().login(mAccount, mPassword, new EMCallBack() {
    // 登录成功回调
    @Override 
    public void onSuccess() {

    }

    // 登录失败回调,包含错误信息
    @Override 
    public void onError(final int code, final String error) {
    
    }
    
    @Override 
    public void onProgress(int i, String s) {
        
    }

});

4. Add friends on the Android side to get the friend list

(1) Add friends:

// 同步方法,会阻塞当前线程。异步方法为 asyncAddContact(String, String, EMCallBack)。
EMClient.getInstance().contactManager().addContact(toAddUsername, reason);

(2) Get the friend list:

// 从服务器获取好友列表。
// 同步方法,会阻塞当前线程。异步方法为 asyncGetAllContactsFromServer(EMValueCallBack)。
List<String> usernames = EMClient.getInstance().contactManager().getAllContactsFromServer();
// 从本地数据库获取好友列表。
List<String> usernames = EMClient.getInstance().contactManager().getContactsFromLocal();

5. Android terminal realizes sending text message

Send a one-on-one chat message

// `content` 为要发送的文本内容,`toChatUsername` 为对方的账号。
EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
// 发送消息
EMClient.getInstance().chatManager().sendMessage(message);

6. The Android terminal realizes receiving messages

You can register to listen to EMMessageListener to receive messages.

The EMMessageListener can be added multiple times, please remember to remove the listener when it is not needed,

As in the activity's onDestroy().

When a new message arrives, you will receive the callback of onMessageReceived, which may be one when the message is received,

It may also be multiple. You can traverse the message queue in this callback, parse and display the received messages.

EMMessageListener msgListener = new EMMessageListener() {

   // 收到消息,遍历消息队列,解析和显示。
   @Override
   public void onMessageReceived(List<EMMessage> messages) {

   }
};
// 注册消息监听
EMClient.getInstance().chatManager().addMessageListener(msgListener);
// 解注册消息监听
EMClient.getInstance().chatManager().removeMessageListener(msgListener);

7. EaseIMKit creates a chat list page

EaseIMKit provides EaseChatFragment, which can be used after adding to Activity and passing corresponding parameters.

The parameters that must be passed to EaseChatFragment are:

conversationId——conversation ID, which refers to the ID of the other party in single chat, and refers to the group and chat room ID in group chat and chat room;

chatType——chat type, integer, which are single chat (1), group chat (2) and chat room (3);

Optional passed parameters are:

history_msg_id——message ID, which is used to locate message ID when querying history records;

isRoaming——Whether to enable roaming, Boolean type, used to mark whether to pull messages from the server first.

@Override
protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main2)                     
       EaseChatFragment chatFragment = new EaseChatFragment();
       Bundle bundle = new Bundle();
       bundle.putString(EaseConstant.EXTRA_CONVERSATION_ID, "环信id");
       bundle.putInt(EaseConstant.EXTRA_CHAT_TYPE, 1);
       chatFragment.setArguments(bundle);
       getSupportFragmentManager().beginTransaction().replace(R.id.container,chatFragment,"chat").commit();                 
}

8. EaseIMKit creates session list page

EaseIMKit provides EaseConversationListFragment, which needs to be added to

Activity. Developers need to handle refresh events (new message, delete message, delete session, etc.).

1. Load session:

public void loadDefaultData() {
      presenter.loadData();
}

2. Set data

 public void setData(List<EaseConversationInfo> data) {
       presenter.sortData(data);
}

3. Delete session

@Override
public void deleteConversation(int position, EaseConversationInfo info) {
      presenter.deleteConversation(position, info);
}

9. EaseIMKit add contact page

EaseIMKit provides EaseContactListFragment, add it and its subclasses to Activity. Developers need to handle refresh events (add contacts, delete contacts, etc.)

1. Set data

public void setData(List<EaseUser> data) {
      presenter.sortData(data);
}

So far, we have completed the integration of the Android SDK and realized the basic functions of IM . I believe that the subsequent optimization with the ability of all friends is not a problem at all. Of course, there may be some strange problems that may not be solved. It is recommended to go to the official website of Huanxin. Contact the official technical support to quickly help you solve the problems you encounter~~

Easemob official website: https://www.easemob.com/

Register Huanxin Account: Register Huanxin Instant Messenger Cloud

Android SDK download: https://www.easemob.com/download/im

Question exchange: https://www.imgeek.net/

Guess you like

Origin blog.csdn.net/huan132456765/article/details/129615068