preface

Distance last aurora essay unconsciously it’s been nearly a year, first and last composition competition, through the Android and I push the brief history of time, this article and the cheek this time once again to participate in, because the project has been very busy and had to use the weekend time to prepare the demo material and writing articles, is bad, forgive me.

Previous article mainly tells the story of my relationship with aurora push, and simply describes the integration and use, as the three projects are using aurora in push me, to understand its also quite a few, pit was stepped on some, of course, have to thank you again for warrior (aurora) for helping me, although this year did not continue to push the business contact, But when I encounter confusion still have to answer, service attitude is unquestionable!

When I was preparing for the essay, I was thinking about what Angle to take, and I wrote an open source project with a former colleague, WeaponApp, which now has 800+ stars.

Involved in technology I not expound one by one, are interested can look at, there is a module by me solely responsible for – the IM module, because has integrated the aurora push, considering the cost and use, ultimately chose the aurora IM, after all is the aurora push large-scale, high concurrency, stable push for technical foundation, and inherit the characteristics. This article will make an introduction of my integration experience and use to quickly achieve an APP with IM function.

show

Here is only a simple demonstration of IM module functions, you can click the link to download, as shown in GIF:

Basic chat features have been implemented, including:

  1. Log in, register, force kick and unregister
  2. View and modify personal information
  3. Find friends and chat
  4. Group chat
  5. Personal Center Display
  6. Delete sessions and clear chat records

New functions will be added later as required.

integration

Since aurora push service has been integrated in the preceding item, there is no need to repeat many things. All you need to do is integrate JMessage related components into the project. For details, please refer to the official website.

1. Import the JMessage JAR package. 2

No.. You can see how smooth the transition from push to IM is!

use

In fact, the process in use is nothing more than to find API on the official website to realize the functions they want according to their business needs. Then I will introduce the functions in the current project.

Register, log in, and log out

This is actually user information management, Aurora IM unified with UserInfo management, internal contains most of the user information:

    protected long userID;
    protected String userName;
    protected String nickname = "";
    protected String avatarMediaID;
    protected String birthday = "";
    protected String signature = "";
    protected String gender = "";
    protected String region = "";
    protected String address = "";
    protected String appkey = null;
    protected String notename = null;
    protected String noteText = null;
    protected int mTime;
    protected Map<String, String> extras = new ConcurrentHashMap();
Copy the code

1. Register

Going to write their own user server at the beginning, in fact it is performed by another developer, but considering the integration, IM user data migration and archiving process trival, simply directly with the user interface of the aurora, actually internal data is very detailed, also supports custom fields, fully meet the daily needs.

JMessageClient.register(userName, password, new JMessageCallBack() {
    @Override
    public void onSuccess(a) {
        registerSuccess(userName);
    }

    @Override
    public void onFailed(int status, String desc) { registerFailed(desc); }});Copy the code

A user name and password are required for registration. After successful registration, the user name and password are sent back to the login page using setResult.

2. Login

JMessageClient.login(userName, password, new JMessageCallBack() {
    @Override
    public void onSuccess(a) {
        loginSuccess(userName);
    }

    @Override
    public void onFailed(int status, String desc) { loginFailed(desc); }});Copy the code

The same as registration, login also requires a user name and password for login. If there is a misunderstanding in the format, the onFailed callback will be triggered, and the corresponding prompt will be displayed. After success, a UserInfo object is saved locally to store the user’s information.

3. The refund

Aurora supports the active logout function, that is:

JMessageClient.logout();
Copy the code

Delete local user information directly, also it supports multiple online at the same time:

If the switch is not turned on and another device logs in, EventBus will send LoginStateChangeEvent to inform the developer that the changed account has been logged in on another device, and it will carry three states:

case user_password_change:
	forcedExit("Account password has been changed.");
	break;
case user_logout:
	forcedExit("Account logged in on another device.");
	break;
case user_deleted:
	forcedExit("Account deleted");
	break;
Copy the code

Deal with it according to your needs.

View and modify information

1. Personal

User information is stored in the local database by calling:

mUserInfo = JMessageClient.getMyInfo();
Copy the code

UserInfo contains all the user’s data. Corresponding to:

JMessageClient.updateMyInfo(UserInfo.Field.gender, mUserInfo, new JMessageCallBack() {
    @Override
    public void onSuccess(a) {}@Override
    public void onFailed(int status, String desc) {}});Copy the code

This is how you modify your own information by passing userinfo.field to distinguish between changing the value of the property.

2. Others

If you need to query a friend’s information, you can use userName to request the query:

JMessageClient.getUserInfo(userName, new GetUserInfoCallback() {
    @Override
    public void gotResult(int status, String desc, UserInfo userInfo) {
        if (status == 0) {
            getViewModel().setUserInfo(userInfo);
        } else{ getViewModel().setError(desc); }}});Copy the code

The specific results are as follows:

If it is personal information, you can directly modify and logout, if it is others can only view and chat with them.

chat

Finally arrived at the core chat function, in fact, it is not complicated to implement, Aurora IM has given a rich API and instructions, enough to complete the basic requirements.

1. Send message

To send a Message, you need to build a Message object, using the underlying text as an example:

final Message message = mConversation.createSendTextMessage(sendContent);
message.setOnSendCompleteCallback(new BasicCallback() {
    @Override
    public void gotResult(int status, String desc) {
        if (status == 0) {
            // Message sent successfully
            MobclickAgent.onEvent(getContext().getApplicationContext(), "send_message", sendContent);
            addSendMessage(message);
            ++curCount;
            setSendContent("");
            getView().scrollToPosition(items.size() - 1);
        } else {
            // Message sending failedToast.makeText(getContext(), desc, Toast.LENGTH_SHORT).show(); }}}); JMessageClient.sendMessage(message);Copy the code

Finally through JmessageClient. SendMessage (message) will be sent message.

2. Receive messages

He uses EventBus directly for callbacks to receive messages.

The fact that EventBus is integrated into his JAR and included in the project is somewhat disappointing. For those of you who have used EventBus, you should know that if you don’t maintain EventBus properly, your logic will be very confusing and it will be very difficult to maintain and expand it.

* Receive message events * Currently only text messages are supported, this will be optimized later * *@paramEvent Indicates the message event */public void onEventMainThread(MessageEvent event) {
    Message message = event.getMessage();
    switch (message.getContentType()) {
        case text:
            // Process text messages
            String userName = ((UserInfo) message.getTargetInfo()).getUserName();
            if (TextUtils.equals(userName, mUserName)) {
                // Update the UI only when the received message is official
                getViewModel().receiveMessage(message);
            }
        default:
            LogUtils.i("office", message.getFromType());
            break; }}Copy the code

Distinguish the type of message entity based on contentType and treat it accordingly. Register and unregister events where messages need to be received.

JMessageClient.registerEventReceiver(this.200);
JMessageClient.unRegisterEventReceiver(this);
Copy the code

3. Single chat

When you chat with others, a Conversation will be established. The message and the object of the Conversation will be stored in the Conversation. The single Conversation will be connected by passing in userName, which shows the uniqueness and importance of userName.

To obtain historical information, I use conversion to obtain all messages and display them on the interface.

mConversation = Conversation.createSingleConversation(userName);
JMessageClient.getUserInfo(userName, this);
if (mConversation == null) {
    getView().finish();
}
// Get all local messages
msgCount = mConversation.getAllMessage().size();
List<Message> messagesFromNewest = mConversation.getMessagesFromNewest(curCount, LIM_COUNT);
curCount = messagesFromNewest.size();
// The first message is in positive order and needs to be reversed
Collections.reverse(messagesFromNewest);
for (Message message : messagesFromNewest) {
    MessageDirect direct = message.getDirect();
    if (direct == MessageDirect.send) {
        addSendMessage(message);
    } else{ addReceiverMessage(message); }}Copy the code

4. The group chat

A group chat is similar to a single chat, but the premise parameter for establishing a session is not userName, but the unique ID of the groupId group.

mConversation = Conversation.createGroupConversation(groupId);
if (mConversation == null) {
    getView().finish();
    return;
}
List<Message> messagesFromNewest = mConversation.getMessagesFromNewest(curCount, LIM_COUNT);
curCount = messagesFromNewest.size();
Collections.reverse(messagesFromNewest);
for (Message message : messagesFromNewest) {
    MessageDirect direct = message.getDirect();
    if (direct == MessageDirect.send) {
        addSendMessage(message);
    } else{ addReceiverMessage(message); }}Copy the code

The code is similar, but the creation process is different.

conclusion

Recently, byte beating wang xin will be launched social software, but blocked the WeChat platform, it is pretty hard, but on the other hand, reflects the widespread social chat applications in various industries, whether financial, education, sales, and other software needs to be an IM as a bridge between users and users, and platform, so as a developer, Still want to learn more about IM related knowledge. Of course, it is best to complete it independently. If you have no experience or temporary ability, or the company urgently needs to integrate IM functions, I suggest you consider aurora IM service. Its push service is quite good, and it is still in continuous maintenance and iteration, so if you have time, you might as well try a wave!

WeaponApp APK download

This article is for the aurora essay competition article