集成环信实现简单聊天功能

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/CrackgmKey/article/details/82381192

废话不多说,先上效果图
这里写图片描述

下面来实现

1.第一步导入jar or so

去环信下载sdk导入到我们的项目中

这里写图片描述
导入完成之后我们区项目的build文件中,android括号的最下方加上以下代码
不然jar无法使用

    sourceSets {
        main {
            jniLibs.srcDir 'libs'
        }
    }

导入完jar包,我们来配置清单中配置环信所需的权限和服务
这里写图片描述
这里写图片描述

将以上内容全部添加到配置清单中之后将图中“你的APPK”处替换成你环信应用的APPK,
另外使用之前不要忘记初始化环信SDk哦

        EMOptions options = new EMOptions();
        options.setAcceptInvitationAlways(false);
        EMClient.getInstance().init(this, options);
        EMClient.getInstance().setDebugMode(true);

到此,配置和前期工作就做完啦,接下来就是撸码了

2.完善基本功能

首先我们先来写一个登陆页面xml

<?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:id="@+id/activity_main" android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.crackgmkey.chat.LoginActivity">


    <EditText
        android:hint="你的用户名" android:padding="15dp"
        android:background="@drawable/log_bg" android:layout_marginTop="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/user_et" />

    <EditText
        android:hint="你的密码" android:padding="15dp"
        android:background="@drawable/log_bg"
        android:layout_width="match_parent" android:layout_marginTop="5dp"
        android:layout_height="wrap_content"     android:id="@+id/pass_et"/>

    <LinearLayout android:orientation="horizontal"
        android:layout_width="match_parent" android:padding="10dp"
        android:layout_height="wrap_content">

        <Button android:layout_weight="1"
            android:id="@+id/bt_login" android:background="@drawable/dd_bg"
            android:layout_width="0dp" android:text="登录"
            android:layout_height="wrap_content" />

        <View android:background="#ee2"
            android:layout_width="2dp"
            android:layout_height="match_parent"/>

        <Button android:layout_weight="1"
            android:id="@+id/bt_reg" android:background="@drawable/dd_bg"
            android:layout_width="0dp" android:text="注册"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

这里写图片描述

登陆页面已经写好 下面来写代码

贴出LoginActivity的代码

package com.crackgmkey.chat;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText etUser,etPass;//用户名和密码窗口
    private Button btReg,btLogin;//登录注册
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        init();
    }
    //初始化控件
    private void init(){
        getLoginExit();
        etUser = (EditText) findViewById(R.id.user_et);
        etPass = (EditText) findViewById(R.id.pass_et);
        btReg = (Button) findViewById(R.id.bt_reg);
        btLogin = (Button) findViewById(R.id.bt_login);
        btReg.setOnClickListener(this);
        btLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_reg:
                regUser();
                break;
            case R.id.bt_login:
                login();
                break;
        }
    }

    /**
     * 注册用户(同步需注意)
     */
    private void regUser(){
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                try {
                    EMClient.getInstance().createAccount(etUser.getText().toString().trim(), etPass.getText().toString().trim());//同步方法
                    subscriber.onNext("注册成功");
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    subscriber.onNext("注册失败错误码:"+e.getErrorCode());
                }
            }
        }).subscribeOn(Schedulers.io())
             .observeOn(AndroidSchedulers.mainThread())
          .subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                Toast.makeText(LoginActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 登录用户(异步)
     */
    private void login(){
        final String userName = etUser.getText().toString().trim();
        final String password = etPass.getText().toString().trim();
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final Subscriber<? super String> subscriber) {
                EMClient.getInstance().login(userName,password,new EMCallBack() {//回调
                    @Override
                    public void onSuccess() {
                        EMClient.getInstance().groupManager().loadAllGroups();
                        EMClient.getInstance().chatManager().loadAllConversations();
                        startActivity(new Intent(LoginActivity.this,MainActivity.class));
                        subscriber.onNext("登录聊天服务器成功");
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }

                    @Override
                    public void onError(int code, String message) {
                        subscriber.onNext("登录聊天服务器失败:"+code);
                    }
                });
            }

        }).subscribeOn(Schedulers.immediate())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                Toast.makeText(LoginActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 退出登录
     */
    private void getLoginExit(){
        EMClient.getInstance().logout(true, new EMCallBack() {
            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub
            }

            @Override
            public void onProgress(int progress, String status) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onError(int code, String message) {
                // TODO Auto-generated method stub
            }
        });
    }
}

该页面包含了登陆和注册,在登录成功的时候会跳转到Mainactivity中,接下来我们来写Mainactivity的代码,首先我们先写好布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.crackgmkey.chat.MainActivity">

    <EditText
        android:id="@+id/et_chatId" android:background="@drawable/chatid"
        android:layout_width="match_parent" android:hint="输入对方用户名" android:layout_marginTop="10dp"
        android:layout_height="40dp" android:padding="10dp" android:layout_marginBottom="20dp"/>

    <Button
        android:layout_below="@+id/et_chatId" android:id="@+id/bt_startChat" android:textColor="@android:color/white"
        android:layout_width="wrap_content" android:text="发起聊天" android:layout_marginLeft="40dp"
        android:layout_height="wrap_content" android:background="@drawable/buttonbg" />

    <Button
        android:layout_below="@+id/et_chatId" android:id="@+id/bt_exit" android:layout_marginLeft="120dp"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content" android:text="退出登录" android:background="@drawable/buttonbg"
        android:layout_height="wrap_content" android:layout_toRightOf="@+id/bt_startChat" />

</RelativeLayout>

效果图

这里写图片描述

很简单,就两个按钮和一个输入框,一个是发起聊天一个是退出登录,点击发起聊天的时候会跳转到一个新的聊天页面,我们来写代码

package com.crackgmkey.chat;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText etChatId;
    private Button btStartChat,btExit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    /**
     * 初始化组件
     */
    private void init() {
        etChatId = (EditText) findViewById(R.id.et_chatId);
        btStartChat = (Button) findViewById(R.id.bt_startChat);
        btExit = (Button) findViewById(R.id.bt_exit);
        btStartChat.setOnClickListener(this);
        btExit.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_exit:
                getLoginExit();
                break;
            case R.id.bt_startChat:
                Intent inetent = new Intent(this,UserChatActivity.class);
                inetent.putExtra("userid",etChatId.getText().toString());
                startActivity(inetent);
                break;
        }
    }

    /**
     * 退出登录
     */
    private void getLoginExit(){
        EMClient.getInstance().logout(true, new EMCallBack() {

            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgress(int progress, String status) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onError(int code, String message) {
                // TODO Auto-generated method stub

            }
        });
    }
}

可以看到代码也是比较简单,只有一个退出的方法和一个跳转的操作,接下来我们来看UserChatActivity的xml布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_user_chat"
    android:layout_width="match_parent" android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context="com.crackgmkey.chat.UserChatActivity">


    <TextView android:id="@+id/tv_messagedata" android:textColor="#000"
        android:layout_width="match_parent" android:layout_above="@+id/messagelay"
        android:layout_height="match_parent" />

    <RelativeLayout android:layout_alignParentBottom="true" android:id="@+id/messagelay"
        android:layout_width="match_parent" android:orientation="horizontal"
        android:layout_height="wrap_content">

        <EditText android:background="@drawable/log_bg"
            android:layout_width="270dp" android:id="@+id/et_chatmessage"
            android:layout_height="40dp" />
        <Button android:text="发送" android:id="@+id/bt_sent"
            android:layout_width="wrap_content" android:layout_toRightOf="@+id/et_chatmessage"
            android:layout_height="wrap_content" />
    </RelativeLayout>
</RelativeLayout>

这里写图片描述
基本就是这个样子,我们来看代码

package com.crackgmkey.chat;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;

import java.util.List;

import rx.Observable;
import rx.functions.Action1;

public class UserChatActivity extends AppCompatActivity implements View.OnClickListener,EMMessageListener {
    private TextView tvMessageData;
    private EditText etChatmess;
    private Button btSent;
    private String userId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_chat);
        userId = getIntent().getExtras().getString("userid");
        init();
        EMClient.getInstance().chatManager().addMessageListener(this);
    }

    /**
     * 初始化控件
     */
    private void init() {
        tvMessageData = (TextView) findViewById(R.id.tv_messagedata);
        etChatmess = (EditText) findViewById(R.id.et_chatmessage);
        btSent = (Button) findViewById(R.id.bt_sent);
        btSent.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_sent:
                sendMessage();
                break;
        }
    }

    /**
     * 发送消息
     */
    private void sendMessage(){
        String messageStr = etChatmess.getText().toString();
        EMMessage messagelay = EMMessage.createTxtSendMessage(messageStr,userId);
        EMClient.getInstance().chatManager().sendMessage(messagelay);
        etChatmess.setText("");
        tvMessageData.append("我:"+messageStr+"\n");
    }


    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        Observable.from(messages).subscribe(new Action1<EMMessage>() {
            @Override
            public void call(EMMessage emMessage) {
                EMTextMessageBody emtextmessage = (EMTextMessageBody) emMessage.getBody();
                tvMessageData.append(emMessage.getFrom()+":"+emtextmessage.getMessage()+"\n");
            }
        });
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {

    }

    @Override
    public void onMessageRead(List<EMMessage> messages) {

    }

    @Override
    public void onMessageDelivered(List<EMMessage> messages) {

    }

    @Override
    public void onMessageChanged(EMMessage message, Object change) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(this);
    }
}

接收消息的回调是onMessageReceived方法,返回的是一个List,到此基本功能就完成了,具体需求请查看环信官方文档
http://docs.easemob.com/im/200androidclientintegration/10androidsdkimport,写的非常靠谱

最后附上demo下载地址:https://download.csdn.net/download/crackgmkey/10644547

展开阅读全文

没有更多推荐了,返回首页