环信聊天的基本集成步骤及遇到的问题

原创 2016年08月29日 21:09:58



        

                      2017.01.10修改了发红包    在红包下面增加了一句xxx收到了xx发的红包,  屏蔽了红包的点击 显示领取红包的消息(具体操作在文章最底部)   


首先下载 环信demo,然后就可以开始集成了:                               我没有使用环信中的红包功能,该红包模块是自己写的  详细介绍请往下看

      根据环信demo总结的基本的集成步骤如下:

             1、根据官方文档 提示的      根据自己需要的功能去 拷贝jar 和 so 库文件

                   本人是拷贝的demo中的arm64-v8a、armeabi、x86 具体为什么  详细请自己去看文档

             2、由于我需要的是  抽取环信中的部分功能  所以 使用了 EaseUI

                   把EaseUI 添加到项目中 作为类库使用,EaseUI时  需要注意   把EaseUI中原有的 build.gradle删掉 

                   可以Import Moudle    也可以  直接把EaseUI 放到 自己的project  的文件夹目录下

                   容易出现以下问题:  jar包重复等  或者   可能会出现 v4包或其他jar包重复(这点其实也没什么可根据编译或者同步时具体报错信息 查找对应的原因)   可以自己手动进行去除   

             3、文档中所描述的 下面这个问题  是肯定会遇到的    

Demo 中用到的第三方库

  • android-support-multidex.jar:APP 总方法数超过 64k 时,需要用这个库做分包处理,可以删除

  也可以不使用这个jar包 ,   直接在自己的 app的gradle中  的defaultConfig中 加入    multiDexEnabled true  其作用与导入multidex.jar 作用相同

                4、还会遇到一些编译的小问题  解决办法  就是修改gradle文件中的  compileSdkVersion  和  buildToolsVersion   即可


                5、拷贝demo中  AndroidManifest.xml 中 使用的权限     和  需要使用的  Activity  等信息  ,本人所用的有部分的

<!-- 设置环信应用的AppKey -->
<meta-data android:name="EASEMOB_APPKEY"  android:value="自己的appkey" />
<!-- 声明SDK所需的service SDK核心功能-->
<service android:name="com.hyphenate.chat.EMChatService" android:exported="true"/>
<!-- 声明SDK所需的receiver -->
<receiver android:name="com.hyphenate.chat.EMMonitorReceiver">
    <intent-filter>
        <action android:name="android.intent.action.PACKAGE_REMOVED"/>
        <data android:scheme="package"/>
    </intent-filter>
    <!-- 可选filter -->
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="android.intent.action.USER_PRESENT" />
    </intent-filter>
</receiver>

<activity android:name=".huanxin.LoginActivity"/>
<!--关于环信的Activity-->
<activity android:name=".huanxin.activity.CallActivity"></activity>
<activity android:name=".huanxin.activity.ChatActivity"></activity>
<activity android:name=".huanxin.activity.ChatRoomDetailsActivity"></activity>
<activity android:name=".huanxin.activity.ContextMenuActivity"></activity>
<activity android:name=".huanxin.activity.GroupDetailsActivity"></activity>
<activity android:name=".huanxin.activity.ImageGridActivity"></activity>
<activity android:name=".huanxin.activity.PickAtUserActivity"></activity>
<activity android:name=".huanxin.activity.RecorderVideoActivity"></activity>
<activity android:name=".huanxin.activity.UserProfileActivity"></activity>
<activity android:name=".huanxin.activity.GroupMemberListActivity"></activity>

<activity android:name=".huanxin.activity.VideoCallActivity"
    android:configChanges="orientation|keyboardHidden|screenSize"
    android:screenOrientation="portrait"
    android:launchMode="singleTask"
    android:theme="@style/horizontal_slide"></activity>
<activity android:name=".huanxin.activity.VoiceCallActivity"
    android:screenOrientation="portrait"
    android:launchMode="singleTask"
    android:theme="@style/nornal_style"></activity>
<activity android:name=".huanxin.GroupsActivity"></activity>



<!--点击观看视频-->
<activity
    android:name="com.hyphenate.easeui.ui.EaseShowVideoActivity"
    android:screenOrientation="portrait"
    android:theme="@style/horizontal_slide"
    android:windowSoftInputMode="stateAlwaysHidden" >
</activity>
<!-- 显示下载大图页面 -->
<activity
    android:name="com.hyphenate.easeui.ui.EaseShowBigImageActivity"
    android:screenOrientation="portrait"
    android:theme="@style/horizontal_slide" >
</activity>
<!-- 下载文件 -->
<activity
    android:name="com.hyphenate.easeui.ui.EaseShowNormalFileActivity"
    android:screenOrientation="portrait"
    android:theme="@style/horizontal_slide" >
</activity>

<!-- 地图 -->
<activity
    android:name="com.hyphenate.easeui.ui.EaseBaiduMapActivity"
    android:screenOrientation="portrait"
    android:theme="@style/horizontal_slide" >
</activity>
<!--群成员列表页-->
<!--<activity-->
    <!--android:name="com.easemob.redpacketui.ui.activity.RPGroupMemberActivity"-->
    <!--android:screenOrientation="portrait"-->
    <!--android:theme="@style/horizontal_slide"-->
    <!--android:windowSoftInputMode="adjustPan|stateHidden"-->
    <!--/>-->
<!-- 百度地图所需的service -->
<service
    android:name="com.baidu.location.f"
    android:enabled="true"
    android:process=":remote" />
<meta-data
    android:name="com.baidu.lbsapi.API_KEY"
    android:value="3ecea51f560650b1ed8a4b99808f52e8" />
 如需详细了解  可参见demo中的具体信息。

              6、参照demo中  的application类    对其进行初始化   如果参照了demo   官方的文档只是 辅助理解的作用

                       如果使用 EaseUI 库  可以去官网  大致了解  easeui 里面的一些界面信息

              7、具体有什么问题或者不明白的  也可以进行   官方的技术咨询。  官网 右下角

需要注意的是   环信demo中 自动处理的登录的问题   :

    就是在自己登录一个号后  如果不手动清理数据  或者  没有实现注销登录      

    就无法登录另外一个号       因为demo中 默认使用的 sp记录   还有一些东西   时间长我忘记了   回头再使用时  再进行补充总结的内容



环信集成后  

     1.clean等问题    

        估计是android studio的问题   多次clean 或者  rebuild  运行就可以了

     2.使用百度地图定位当前经纬度的问题: 

        自己测试是5.0以下手机出现的   会报百度地图初始化的问题

在自己的  Application类的  oncreate 方法中   对百度地图的sdk进行初始化, 但是在本项目中使用百度地图会出现问题,可在环信的 easeui 中把 百度地图的 .so 库文件等放到已存在的或者自己创建的 jniLibs 目录下:

     

然后需要在  easeui 的 build.gradle  的  android 节点的 

sourceSets {
    main {
        jniLibs.srcDirs = ['libs','jniLibs']
    }
}
可以根据自己的需要  更新百度地图的jar包  和 .so库文件     更新后如果环信 EaseBaiduMapActivity 中报错:

   

//  public NotifyLister mNotifyer = null;
//import com.baidu.location.BDNotifyListener;

 把报错的地方  注释掉就可以了


关于环信中聊天界面的扩展菜单:

ChatFragment中
onExtendMenuItemClick 方法

里面有

ITEM_VIDEO   
ITEM_FILE
ITEM_VOICE_CALL
ITEM_RED_PACKET
等扩展的 选项  ------

 可进入对应的界面


红包功能的实现:

package com.basedemo.my.xi.basedemo.huanxin.hongbao;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.basedemo.my.xi.basedemo.R;
import com.basedemo.my.xi.basedemo.huanxin.Constant;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;

public class ChatRowRedPacket extends EaseChatRow {

    private TextView mTvGreeting;
    private TextView mTvSponsorName;
    private TextView mTvPacketType;

    public ChatRowRedPacket(Context context, EMMessage message, int position, BaseAdapter adapter) {
        super(context, message, position, adapter);
    }

    @Override
    protected void onInflatView() {
        if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {
            inflater.inflate(message.direct() == EMMessage.Direct.RECEIVE ?
                    R.layout.em_row_received_red_packet : R.layout.em_row_sent_red_packet, this);
        }
    }

    @Override
    protected void onFindViewById() {
        mTvGreeting = (TextView) findViewById(R.id.tv_money_greeting);
        mTvSponsorName = (TextView) findViewById(R.id.tv_sponsor_name);
        mTvPacketType = (TextView) findViewById(R.id.tv_packet_type);
    }

    @Override
    protected void onSetUpView() {
        String sponsorName = message.getStringAttribute(RedPacketConstant.EXTRA_SPONSOR_NAME, "");
        String greetings = message.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_GREETING, "");
        mTvGreeting.setText(greetings);
        mTvSponsorName.setText(sponsorName);
        String packetType = message.getStringAttribute(RedPacketConstant.MESSAGE_ATTR_RED_PACKET_TYPE, "");
        if (!TextUtils.isEmpty(packetType) && TextUtils.equals(packetType, RedPacketConstant.GROUP_RED_PACKET_TYPE_EXCLUSIVE)) {
            mTvPacketType.setVisibility(VISIBLE);
            mTvPacketType.setText("专属红包");
        } else {
            mTvPacketType.setVisibility(GONE);
        }
        handleTextMessage();
    }

    protected void handleTextMessage() {
        if (message.direct() == EMMessage.Direct.SEND) {
            setMessageSendCallback();
            switch (message.status()) {
                case CREATE:
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.VISIBLE);
                    // 发送消息
                    break;
                case SUCCESS: // 发送成功
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.GONE);
                    break;
                case FAIL: // 发送失败
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.VISIBLE);
                    break;
                case INPROGRESS: // 发送中
                    progressBar.setVisibility(View.VISIBLE);
                    statusView.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onUpdateView() {
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onBubbleClick() {
    }

}

package com.basedemo.my.xi.basedemo.huanxin.hongbao;

import android.content.Context;
import android.widget.BaseAdapter;
import android.widget.TextView;

//import com.easemob.redpacketui.R;
//import com.easemob.redpacketui.RedPacketConstant;
import com.basedemo.my.xi.basedemo.R;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;

public class ChatRowRedPacketAck extends EaseChatRow {

    private TextView mTvMessage;

    public ChatRowRedPacketAck(Context context, EMMessage message, int position, BaseAdapter adapter) {
        super(context, message, position, adapter);
    }

    @Override
    protected void onInflatView() {
        if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {
            inflater.inflate(message.direct() == EMMessage.Direct.RECEIVE ?
                    R.layout.em_row_red_packet_ack_message : R.layout.em_row_red_packet_ack_message, this);
        }
    }

    @Override
    protected void onFindViewById() {
        mTvMessage = (TextView) findViewById(R.id.ease_tv_money_msg);
    }

    @Override
    protected void onSetUpView() {
        String currentUser = EMClient.getInstance().getCurrentUser();
        String fromUser = message.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_NAME, "");//红包发送者
        String toUser = message.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_RECEIVER_NAME, "");//红包接收者
        String senderId;
        if (message.direct() == EMMessage.Direct.SEND) {
            if (message.getChatType().equals(EMMessage.ChatType.GroupChat)) {
                senderId = message.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_ID, "");
                if (senderId.equals(currentUser)) {
                    mTvMessage.setText(R.string.msg_take_red_packet);
                } else {
                    mTvMessage.setText(String.format(getResources().getString(R.string.msg_take_someone_red_packet), fromUser));
                }
            } else {
                mTvMessage.setText(String.format(getResources().getString(R.string.msg_take_someone_red_packet), toUser));
            }
        } else {
            mTvMessage.setText(String.format(getResources().getString(R.string.msg_someone_take_red_packet), toUser));
        }
    }

    @Override
    protected void onUpdateView() {

    }

    @Override
    protected void onBubbleClick() {
    }

}
package com.basedemo.my.xi.basedemo.huanxin.hongbao;

/**
 * Created by max on 16/5/24.
 */
public class RedPacketConstant {
    //以下常量值切勿更改
    public static final String REFRESH_GROUP_RED_PACKET_ACTION = "refresh_group_money_action";
    public static final String EXTRA_RED_PACKET_SENDER_ID = "money_sender_id";
    public static final String EXTRA_RED_PACKET_RECEIVER_ID = "money_receiver_id";
    public static final String MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE = "is_open_money_msg";
    public static final String MESSAGE_ATTR_IS_RED_PACKET_MESSAGE = "is_money_msg";
    public static final String EXTRA_RED_PACKET_SENDER_NAME = "money_sender";
    public static final String EXTRA_RED_PACKET_RECEIVER_NAME = "money_receiver";
    public static final String EXTRA_SPONSOR_NAME = "money_sponsor_name";
    public static final String EXTRA_RED_PACKET_GREETING = "money_greeting";
    public static final String EXTRA_RED_PACKET_ID = "ID";
    public static final String EXTRA_RED_PACKET_GROUP_ID = "money_from_group_id";
    public static final String MESSAGE_ATTR_RED_PACKET_TYPE = "money_type_special";
    public static final String GROUP_RED_PACKET_TYPE_EXCLUSIVE = "member";
    public static final String MESSAGE_ATTR_SPECIAL_RECEIVER_ID = "special_money_receiver_id";
    public static final String EXTRA_RED_PACKET_TYPE = "red_packet_type";
}
package com.basedemo.my.xi.basedemo.huanxin.hongbao;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.widget.Toast;

//import com.easemob.redpacketsdk.bean.RPUserBean;
//import com.easemob.redpacketsdk.bean.RedPacketInfo;
//import com.easemob.redpacketsdk.bean.TokenData;
//import com.easemob.redpacketsdk.constant.RPConstant;
//import com.easemob.redpacketui.R;
//import com.easemob.redpacketui.RedPacketConstant;
//import com.easemob.redpacketui.callback.GroupMemberCallback;
//import com.easemob.redpacketui.callback.NotifyGroupMemberCallback;
//import com.easemob.redpacketui.ui.activity.RPChangeActivity;
//import com.easemob.redpacketui.ui.activity.RPRedPacketActivity;
import com.basedemo.my.xi.basedemo.R;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.widget.EaseChatMessageList;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by max on 16/5/24.
 */
public class RedPacketUtil {

    /**
     * 进入发红包页面
     *
     * @param fragment
     * @param chatType
     * @param toChatUsername
     * @param requestCode
     */
    public static void startRedPacketActivityForResult(Fragment fragment, int chatType, final String toChatUsername, int requestCode) {
        //发送者头像url
        String fromAvatarUrl = "none";
        //发送者昵称 设置了昵称就传昵称 否则传id
        String fromNickname = EMClient.getInstance().getCurrentUser();
        EaseUser easeUser = EaseUserUtils.getUserInfo(fromNickname);
        if (easeUser != null) {
            fromAvatarUrl = TextUtils.isEmpty(easeUser.getAvatar()) ? "none" : easeUser.getAvatar();
            fromNickname = TextUtils.isEmpty(easeUser.getNick()) ? easeUser.getUsername() : easeUser.getNick();
        }
//        RedPacketInfo redPacketInfo = new RedPacketInfo();
//        redPacketInfo.fromAvatarUrl = fromAvatarUrl;
//        redPacketInfo.fromNickName = fromNickname;
//        //接收者Id或者接收的群Id
//        if (chatType == EaseConstant.CHATTYPE_SINGLE) {
//            redPacketInfo.toUserId = toChatUsername;
//            redPacketInfo.chatType = RPConstant.CHATTYPE_SINGLE;
//        } else if (chatType == EaseConstant.CHATTYPE_GROUP) {
//            //拉取最新群组数据
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        EMClient.getInstance().groupManager().getGroupFromServer(toChatUsername);
//                    } catch (HyphenateException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }).start();
//            RPGroupMemberUtil.getInstance().setGroupMemberListener(new NotifyGroupMemberCallback() {
//                @Override
//                public void getGroupMember(final String groupID, final GroupMemberCallback mCallBack) {
//                    EMGroup group = EMClient.getInstance().groupManager().getGroup(groupID);
//                    List<String> members = group.getMembers();
//                    List<RPUserBean> userBeanList = new ArrayList<RPUserBean>();
//                    EaseUser user;
//                    for (int i = 0; i < members.size(); i++) {
//                        RPUserBean userBean = new RPUserBean();
//                        userBean.userId = members.get(i);
//                        if (userBean.userId.equals(EMClient.getInstance().getCurrentUser())) {
//                            continue;
//                        }
//                        user = EaseUserUtils.getUserInfo(userBean.userId);
//                        if (user != null) {
//                            userBean.userAvatar = TextUtils.isEmpty(user.getAvatar()) ? "none" : user.getAvatar();
//                            userBean.userNickname = TextUtils.isEmpty(user.getNick()) ? user.getUsername() : user.getNick();
//                        } else {
//                            userBean.userNickname = userBean.userId;
//                            userBean.userAvatar = "none";
//                        }
//                        userBeanList.add(userBean);
//                    }
//                    mCallBack.setGroupMember(userBeanList);
//                }
//            });
//            EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
//            redPacketInfo.toGroupId = group.getGroupId();
//            redPacketInfo.groupMemberCount = group.getAffiliationsCount();
//            redPacketInfo.chatType = RPConstant.CHATTYPE_GROUP;
//        }
//        Intent intent = new Intent(fragment.getContext(), RPRedPacketActivity.class);
//        intent.putExtra(RPConstant.EXTRA_RED_PACKET_INFO, redPacketInfo);
//        intent.putExtra(RPConstant.EXTRA_TOKEN_DATA, getTokenData());
//        fragment.startActivityForResult(intent, requestCode);
    }

//    @NonNull
//    private static TokenData getTokenData() {
//        TokenData tokenData = new TokenData();
//        tokenData.imUserId = EMClient.getInstance().getCurrentUser();
//        //此处使用环信id代替了appUserId 开发者可传入App的appUserId
//        tokenData.appUserId = EMClient.getInstance().getCurrentUser();
//        tokenData.imToken = EMClient.getInstance().getChatConfig().getAccessToken();
//        return tokenData;
//    }

    /**
     * 创建一条红包消息
     *
     * @param context        上下文
     * @param data           intent
     * @param toChatUsername 消息接收者id
     * @return
     */
    public static EMMessage createRPMessage(Context context, Intent data, String toChatUsername) {
        String greetings = data.getStringExtra(RedPacketConstant.EXTRA_RED_PACKET_GREETING);
        String moneyID = data.getStringExtra(RedPacketConstant.EXTRA_RED_PACKET_ID);
        String specialReceiveId = data.getStringExtra(RedPacketConstant.EXTRA_RED_PACKET_RECEIVER_ID);
        String redPacketType = data.getStringExtra(RedPacketConstant.EXTRA_RED_PACKET_TYPE);
        EMMessage message = EMMessage.createTxtSendMessage("[" + context.getResources().getString(R.string.easemob_red_packet) + "]" + greetings, toChatUsername);
        message.setAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, true);
        message.setAttribute(RedPacketConstant.EXTRA_SPONSOR_NAME, context.getResources().getString(R.string.easemob_red_packet));
        message.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_GREETING, greetings);
        message.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_ID, moneyID);
        message.setAttribute(RedPacketConstant.MESSAGE_ATTR_RED_PACKET_TYPE, redPacketType);
        message.setAttribute(RedPacketConstant.MESSAGE_ATTR_SPECIAL_RECEIVER_ID, specialReceiveId);
        return message;
    }

    /**
     * 拆红包的方法
     *
     * @param activity       FragmentActivity
     * @param chatType       聊天类型
     * @param message        EMMessage
     * @param toChatUsername 消息接收者id
     * @param messageList
     * @return
     */
    public static void openRedPacket(final FragmentActivity activity, final int chatType, final EMMessage message, final String toChatUsername, final EaseChatMessageList messageList) {
        final ProgressDialog progressDialog = new ProgressDialog(activity);
        progressDialog.setCanceledOnTouchOutside(false);
        String messageDirect;
        //接收者头像url 默认值为none
        String toAvatarUrl = "none";//测试用图片url:http://i.imgur.com/DvpvklR.png
        //接收者昵称 默认值为当前用户ID
        String toNickname = EMClient.getInstance().getCurrentUser();
        String currentUserId = toNickname;
        String moneyId = message.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_ID, "");
//        if (message.direct() == EMMessage.Direct.SEND) {
//            messageDirect = RPConstant.MESSAGE_DIRECT_SEND;
//        } else {
//            messageDirect = RPConstant.MESSAGE_DIRECT_RECEIVE;
//        }
//        EaseUser easeUser = EaseUserUtils.getUserInfo(EMClient.getInstance().getCurrentUser());
//        if (easeUser != null) {
//            toAvatarUrl = TextUtils.isEmpty(easeUser.getAvatar()) ? "none" : easeUser.getAvatar();
//            toNickname = TextUtils.isEmpty(easeUser.getNick()) ? easeUser.getUsername() : easeUser.getNick();
//        }
//        String specialAvatarUrl = "none";
//        String specialNickname = "";
//        String packetType;
//        packetType = message.getStringAttribute(RedPacketConstant.MESSAGE_ATTR_RED_PACKET_TYPE, "");
//        String specialReceiveId = message.getStringAttribute(RedPacketConstant.MESSAGE_ATTR_SPECIAL_RECEIVER_ID, "");
//        if (!TextUtils.isEmpty(packetType) && packetType.equals(RedPacketConstant.GROUP_RED_PACKET_TYPE_EXCLUSIVE)) {
//            EaseUser userInfo = EaseUserUtils.getUserInfo(specialReceiveId);
//            if (userInfo != null) {
//                specialAvatarUrl = TextUtils.isEmpty(userInfo.getAvatar()) ? "none" : userInfo.getAvatar();
//                specialNickname = TextUtils.isEmpty(userInfo.getNick()) ? userInfo.getUsername() : userInfo.getNick();
//            } else {
//                specialNickname = specialReceiveId;
//            }
//        }
//        RedPacketInfo redPacketInfo = new RedPacketInfo();
//        redPacketInfo.moneyID = moneyId;
//        redPacketInfo.toAvatarUrl = toAvatarUrl;
//        redPacketInfo.toNickName = toNickname;
//        redPacketInfo.moneyMsgDirect = messageDirect;
//        redPacketInfo.toUserId = currentUserId;
//        redPacketInfo.chatType = chatType;
//        if (packetType.equals(RedPacketConstant.GROUP_RED_PACKET_TYPE_EXCLUSIVE)) {
//            redPacketInfo.specialAvatarUrl = specialAvatarUrl;
//            redPacketInfo.specialNickname = specialNickname;
//        }
//        RPOpenPacketUtil.getInstance().openRedPacket(redPacketInfo, getTokenData(), activity, new RPOpenPacketUtil.RPOpenPacketCallBack() {
//            @Override
//            public void onSuccess(String senderId, String senderNickname) {
//                //领取红包成功 发送消息到聊天窗口
//                String receiverId = EMClient.getInstance().getCurrentUser();
//                //设置默认值为id
//                String receiverNickname = receiverId;
//                EaseUser receiverUser = EaseUserUtils.getUserInfo(receiverId);
//                if (receiverUser != null) {
//                    receiverNickname = TextUtils.isEmpty(receiverUser.getNick()) ? receiverUser.getUsername() : receiverUser.getNick();
//                }
//                if (chatType == EaseConstant.CHATTYPE_SINGLE) {
//                    EMMessage msg = EMMessage.createTxtSendMessage(String.format(activity.getResources().getString(R.string.msg_someone_take_red_packet), receiverNickname), toChatUsername);
//                    msg.setAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, true);
//                    msg.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_RECEIVER_NAME, receiverNickname);
//                    msg.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_NAME, senderNickname);
//                    EMClient.getInstance().chatManager().sendMessage(msg);
//                } else {
//                    sendRedPacketAckMessage(message, senderId, senderNickname, receiverId, receiverNickname, new EMCallBack() {
//                        @Override
//                        public void onSuccess() {
//                            messageList.refresh();
//                        }
//
//                        @Override
//                        public void onError(int i, String s) {
//
//                        }
//
//                        @Override
//                        public void onProgress(int i, String s) {
//
//                        }
//                    });
//                }
//            }
//
//            @Override
//            public void showLoading() {
//                progressDialog.show();
//            }
//
//            @Override
//            public void hideLoading() {
//                progressDialog.dismiss();
//            }
//
//            @Override
//            public void onError(String code, String message) {
//                Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    /**
     * 进入零钱页面
     *
     * @param context 上下文
     */
    public static void startChangeActivity(Context context) {
//        Intent intent = new Intent(context, RPChangeActivity.class);
//        String fromNickname = EMClient.getInstance().getCurrentUser();
//        String fromAvatarUrl = "none";
//        EaseUser easeUser = EaseUserUtils.getUserInfo(fromNickname);
//        if (easeUser != null) {
//            fromAvatarUrl = TextUtils.isEmpty(easeUser.getAvatar()) ? "none" : easeUser.getAvatar();
//            fromNickname = TextUtils.isEmpty(easeUser.getNick()) ? easeUser.getUsername() : easeUser.getNick();
//        }
//        RedPacketInfo redPacketInfo = new RedPacketInfo();
//        redPacketInfo.fromNickName = fromNickname;
//        redPacketInfo.fromAvatarUrl = fromAvatarUrl;
//        intent.putExtra(RPConstant.EXTRA_RED_PACKET_INFO, redPacketInfo);
//        intent.putExtra(RPConstant.EXTRA_TOKEN_DATA, getTokenData());
//        context.startActivity(intent);
    }


    /**
     * 使用cmd消息发送领到红包之后的回执消息
     */
    private static void sendRedPacketAckMessage(final EMMessage message, final String senderId, final String senderNickname, String receiverId, final String receiverNickname, final EMCallBack callBack) {
        //创建透传消息
        final EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
        cmdMsg.setChatType(EMMessage.ChatType.Chat);
        EMCmdMessageBody cmdBody = new EMCmdMessageBody(RedPacketConstant.REFRESH_GROUP_RED_PACKET_ACTION);
        cmdMsg.addBody(cmdBody);
        cmdMsg.setReceipt(senderId);
        //设置扩展属性
        cmdMsg.setAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, true);
        cmdMsg.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_NAME, senderNickname);
        cmdMsg.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_RECEIVER_NAME, receiverNickname);
        cmdMsg.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_ID, senderId);
        cmdMsg.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_RECEIVER_ID, receiverId);
        cmdMsg.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_GROUP_ID, message.getTo());
        cmdMsg.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                //保存消息到本地
                EMMessage sendMessage = EMMessage.createTxtSendMessage("content", message.getTo());
                sendMessage.setChatType(EMMessage.ChatType.GroupChat);
                sendMessage.setFrom(message.getFrom());
                sendMessage.setTo(message.getTo());
                sendMessage.setMsgId(UUID.randomUUID().toString());
                sendMessage.setMsgTime(cmdMsg.getMsgTime());
                sendMessage.setUnread(false);//去掉未读的显示
                sendMessage.setDirection(EMMessage.Direct.SEND);
                sendMessage.setAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, true);
                sendMessage.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_NAME, senderNickname);
                sendMessage.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_RECEIVER_NAME, receiverNickname);
                sendMessage.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_ID, senderId);
                EMClient.getInstance().chatManager().saveMessage(sendMessage);
                callBack.onSuccess();
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
        EMClient.getInstance().chatManager().sendMessage(cmdMsg);
    }

    /**
     * 使用cmd消息收取领到红包之后的回执消息
     */
    public static void receiveRedPacketAckMessage(EMMessage message) {
        String senderNickname = message.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_NAME, "");
        String receiverNickname = message.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_RECEIVER_NAME, "");
        String senderId = message.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_ID, "");
        String receiverId = message.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_RECEIVER_ID, "");
        String groupId = message.getStringAttribute(RedPacketConstant.EXTRA_RED_PACKET_GROUP_ID, "");
        String currentUser = EMClient.getInstance().getCurrentUser();
        //更新UI为 xx领取了你的红包
        if (currentUser.equals(senderId) && !receiverId.equals(senderId)) {//如果不是自己领取的红包更新此类消息UI
            EMMessage msg = EMMessage.createTxtSendMessage("content", groupId);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(message.getFrom());
            if (TextUtils.isEmpty(groupId)) {
                msg.setTo(message.getTo());
            } else {
                msg.setTo(groupId);
            }
            msg.setMsgId(UUID.randomUUID().toString());
            msg.setMsgTime(message.getMsgTime());
            msg.setDirection(EMMessage.Direct.RECEIVE);
            msg.setUnread(false);//去掉未读的显示
            msg.setAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, true);
            msg.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_NAME, senderNickname);
            msg.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_RECEIVER_NAME, receiverNickname);
            msg.setAttribute(RedPacketConstant.EXTRA_RED_PACKET_SENDER_ID, senderId);
            //保存消息
            EMClient.getInstance().chatManager().saveMessage(msg);
        }
    }
}

sent_red_packet   xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:gravity="center_horizontal"
              android:orientation="vertical"
              android:paddingTop="13dp"
    >

    <TextView
        android:id="@+id/timestamp"
        style="@style/chat_text_date_style"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <TextView
        android:id="@+id/tv_me"
        android:layout_gravity="right"
        style="@style/right_name_text_style"
        />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/margin_chat_activity"
        >

        <!--<ImageView-->
            <!--android:id="@+id/iv_userhead"-->
            <!--android:layout_width="@dimen/size_avatar"-->
            <!--android:layout_height="@dimen/size_avatar"-->
            <!--android:layout_alignParentRight="true"-->
            <!--android:layout_alignParentTop="true"-->
            <!--android:layout_marginRight="@dimen/margin_chat_activity"-->
            <!--android:src="@drawable/ease_default_avatar"-->
            <!--/>-->
        <ImageView
            android:id="@+id/iv_userhead"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            style="@style/right_dian_style"
            android:src="@drawable/dot"
            />

        <RelativeLayout
            android:id="@+id/bubble"
            android:layout_width="180dp"
            android:layout_height="90dp"
            android:layout_marginRight="@dimen/margin_chat_activity"
            android:layout_toLeftOf="@id/iv_userhead"
            android:background="@drawable/em_red_packet_chatto_bg"
            >

            <ImageView
                android:id="@+id/iv_money_icon"
                style="@style/RedPacketIconStyle"
                android:src="@drawable/em_red_packet_icon"
                />

            <TextView
                android:id="@+id/tv_money_greeting"
                style="@style/RedPacketGreetingStyle"
                />
            <!--android:text="恭喜发财,大吉大利!"-->

            <TextView
                style="@style/RedPacketCheckStyle"
                android:text="发送了指定红包"
                />

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="20dp"
                android:layout_alignParentBottom="true"
                >

                <TextView
                    android:id="@+id/tv_sponsor_name"
                    style="@style/RedPacketSponsorStyle"
                    />

                <TextView
                    android:id="@+id/tv_packet_type"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="3dp"
                    android:textColor="#D24F44"
                    android:textSize="12sp"
                    android:visibility="gone"
                    />

                <ImageView
                    style="@style/RedPacketSponsorIconStyle"
                    />
            </RelativeLayout>
        </RelativeLayout>

        <ImageView
            android:id="@+id/msg_status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@id/bubble"
            android:clickable="true"
            android:src="@drawable/ease_msg_state_failed_resend"
            android:visibility="gone"
            />

        <TextView
            android:id="@+id/tv_ack"
            style="@style/chat_text_name_style"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@id/bubble"
            android:text="@string/text_ack_msg"
            android:textSize="12sp"
            android:visibility="invisible"
            />

        <TextView
            android:id="@+id/tv_delivered"
            style="@style/chat_text_name_style"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@id/tv_chatcontent"
            android:text="@string/text_delivered_msg"
            android:textSize="12sp"
            android:visibility="invisible"
            />

        <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@id/bubble"
            android:visibility="gone"
            />
    </RelativeLayout>

</LinearLayout>

received_red_packet    xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:gravity="center_horizontal"
              android:orientation="vertical"
              android:paddingTop="13dp"
    >

    <TextView
        android:id="@+id/timestamp"
        style="@style/chat_text_date_style"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <TextView
        android:id="@+id/tv_me"
        android:layout_gravity="right"
        style="@style/right_name_text_style"
        />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/margin_chat_activity"
        >

        <!--<ImageView-->
            <!--android:id="@+id/iv_userhead"-->
            <!--android:layout_width="@dimen/size_avatar"-->
            <!--android:layout_height="@dimen/size_avatar"-->
            <!--android:layout_alignParentRight="true"-->
            <!--android:layout_alignParentTop="true"-->
            <!--android:layout_marginRight="@dimen/margin_chat_activity"-->
            <!--android:src="@drawable/ease_default_avatar"-->
            <!--/>-->
        <ImageView
            android:id="@+id/iv_userhead"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            style="@style/right_dian_style"
            android:src="@drawable/dot"
            />

        <RelativeLayout
            android:id="@+id/bubble"
            android:layout_width="180dp"
            android:layout_height="90dp"
            android:layout_marginRight="@dimen/margin_chat_activity"
            android:layout_toLeftOf="@id/iv_userhead"
            android:background="@drawable/em_red_packet_chatto_bg"
            >

            <ImageView
                android:id="@+id/iv_money_icon"
                style="@style/RedPacketIconStyle"
                android:src="@drawable/em_red_packet_icon"
                />

            <TextView
                android:id="@+id/tv_money_greeting"
                style="@style/RedPacketGreetingStyle"
                />
            <!--android:text="恭喜发财,大吉大利!"-->

            <TextView
                style="@style/RedPacketCheckStyle"
                android:text="发送了指定红包"
                />

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="20dp"
                android:layout_alignParentBottom="true"
                >

                <TextView
                    android:id="@+id/tv_sponsor_name"
                    style="@style/RedPacketSponsorStyle"
                    />

                <TextView
                    android:id="@+id/tv_packet_type"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="3dp"
                    android:textColor="#D24F44"
                    android:textSize="12sp"
                    android:visibility="gone"
                    />

                <ImageView
                    style="@style/RedPacketSponsorIconStyle"
                    />
            </RelativeLayout>
        </RelativeLayout>

        <ImageView
            android:id="@+id/msg_status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@id/bubble"
            android:clickable="true"
            android:src="@drawable/ease_msg_state_failed_resend"
            android:visibility="gone"
            />

        <TextView
            android:id="@+id/tv_ack"
            style="@style/chat_text_name_style"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@id/bubble"
            android:text="@string/text_ack_msg"
            android:textSize="12sp"
            android:visibility="invisible"
            />

        <TextView
            android:id="@+id/tv_delivered"
            style="@style/chat_text_name_style"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@id/tv_chatcontent"
            android:text="@string/text_delivered_msg"
            android:textSize="12sp"
            android:visibility="invisible"
            />

        <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@id/bubble"
            android:visibility="gone"
            />
    </RelativeLayout>

</LinearLayout>

点击发送后  回聊天界面:

 

RedPacketConstant.EXTRA_RED_PACKET_GREETING,tv_desc.getText().toString().trim()   // 这个是 对红包的描述   恭喜发财之类的文字

                        Intent intent = new Intent(mContext,ChatActivity.class);
                        intent.putExtra(RedPacketConstant.EXTRA_RED_PACKET_GREETING,tv_desc.getText().toString().trim());
                        setResult(RESULT_OK,intent);
//                setResult(RESULT_OK,new Intent(mContext,ChatActivity.class));
                        finish();


这个是 修改后的  : ChatFragment 

package com.basedemo.my.xi.basedemo.huanxin.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.basedemo.my.xi.basedemo.R;
import com.basedemo.my.xi.basedemo.huanxin.Constant;
import com.basedemo.my.xi.basedemo.huanxin.DemoHelper;
import com.basedemo.my.xi.basedemo.huanxin.domain.EmojiconExampleGroupData;
import com.basedemo.my.xi.basedemo.huanxin.domain.RobotUser;
import com.basedemo.my.xi.basedemo.huanxin.hongbao.ChatRowRedPacket;
import com.basedemo.my.xi.basedemo.huanxin.hongbao.ChatRowRedPacketAck;
import com.basedemo.my.xi.basedemo.huanxin.hongbao.RedPacketConstant;
import com.basedemo.my.xi.basedemo.huanxin.hongbao.RedPacketUtil;
import com.basedemo.my.xi.basedemo.huanxin.widget.ChatRowVoiceCall;
import com.basedemo.my.xi.basedemo.utils.ActivityUtils;
import com.basedemo.my.xi.basedemo.utils.LogUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.ui.EaseChatFragment.EaseChatFragmentHelper;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.easeui.widget.emojicon.EaseEmojiconMenu;
import com.hyphenate.util.EasyUtils;
import com.hyphenate.util.PathUtil;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

public class ChatFragment extends EaseChatFragment implements EaseChatFragmentHelper {

   // constant start from 11 to avoid conflict with constant in base class
    private static final int ITEM_VIDEO = 11;
    private static final int ITEM_FILE = 12;
    private static final int ITEM_VOICE_CALL = 13;
    private static final int ITEM_VIDEO_CALL = 14;

    private static final int REQUEST_CODE_SELECT_VIDEO = 11;
    private static final int REQUEST_CODE_SELECT_FILE = 12;
    private static final int REQUEST_CODE_GROUP_DETAIL = 13;
    private static final int REQUEST_CODE_CONTEXT_MENU = 14;
    private static final int REQUEST_CODE_SELECT_AT_USER = 15;
    

    private static final int MESSAGE_TYPE_SENT_VOICE_CALL = 1;
    private static final int MESSAGE_TYPE_RECV_VOICE_CALL = 2;
    private static final int MESSAGE_TYPE_SENT_VIDEO_CALL = 3;
    private static final int MESSAGE_TYPE_RECV_VIDEO_CALL = 4;

    //red packet code : 红包功能使用的常量
    private static final int MESSAGE_TYPE_RECV_RED_PACKET = 5;
    private static final int MESSAGE_TYPE_SEND_RED_PACKET = 6;
    private static final int MESSAGE_TYPE_SEND_RED_PACKET_ACK = 7;
    private static final int MESSAGE_TYPE_RECV_RED_PACKET_ACK = 8;
    private static final int REQUEST_CODE_SEND_RED_PACKET = 16;
    private static final int ITEM_RED_PACKET = 16;
    //end of red packet code

    /**
     * if it is chatBot 
     */
    private boolean isRobot;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void setUpView() {
        setChatFragmentListener(this);
        if (chatType == Constant.CHATTYPE_SINGLE) {
            Map<String,RobotUser> robotMap = DemoHelper.getInstance().getRobotList();
            if(robotMap!=null && robotMap.containsKey(toChatUsername)){
                isRobot = true;
            }
        }
        super.setUpView();
        // set click listener
        titleBar.setLeftLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (EasyUtils.isSingleActivity(getActivity())) {
//                    Intent intent = new Intent(getActivity(), MainActivity.class);
//                    startActivity(intent);
                }
                onBackPressed();
            }
        });
        ((EaseEmojiconMenu)inputMenu.getEmojiconMenu()).addEmojiconGroup(EmojiconExampleGroupData.getData());
        if(chatType == EaseConstant.CHATTYPE_GROUP){
            inputMenu.getPrimaryMenu().getEditText().addTextChangedListener(new TextWatcher() {
                
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if(count == 1 && "@".equals(String.valueOf(s.charAt(start)))){
                        startActivityForResult(new Intent(getActivity(), PickAtUserActivity.class).
                                putExtra("groupId", toChatUsername), REQUEST_CODE_SELECT_AT_USER);
                    }
                }
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    
                }
                @Override
                public void afterTextChanged(Editable s) {
                    
                } 
            });
        }
    }
    
    @Override
    protected void registerExtendMenuItem() {
        //use the menu in base class
        super.registerExtendMenuItem();
        //extend menu items
        inputMenu.registerExtendMenuItem(R.string.attach_video, R.drawable.em_chat_video_selector, ITEM_VIDEO, extendMenuItemClickListener);
        inputMenu.registerExtendMenuItem(R.string.attach_file, R.drawable.em_chat_file_selector, ITEM_FILE, extendMenuItemClickListener);
        if(chatType == Constant.CHATTYPE_SINGLE){
            inputMenu.registerExtendMenuItem(R.string.attach_voice_call, R.drawable.em_chat_voice_call_selector, ITEM_VOICE_CALL, extendMenuItemClickListener);
            inputMenu.registerExtendMenuItem(R.string.attach_video_call, R.drawable.em_chat_video_call_selector, ITEM_VIDEO_CALL, extendMenuItemClickListener);
        }
        //聊天室暂时不支持红包功能
        //red packet code : 注册红包菜单选项
        // TODO 注册红包菜单选项    聊天室暂时不支持红包功能
        if (chatType != Constant.CHATTYPE_CHATROOM) {
            inputMenu.registerExtendMenuItem(R.string.attach_hongbao, R.drawable.ease_chat_hongbao_selector, ITEM_RED_PACKET, extendMenuItemClickListener);
        }
        //end of red packet code
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
            switch (resultCode) {
            case ContextMenuActivity.RESULT_CODE_COPY: // copy
                clipboard.setPrimaryClip(ClipData.newPlainText(null,
                        ((EMTextMessageBody) contextMenuMessage.getBody()).getMessage()));
                break;
            case ContextMenuActivity.RESULT_CODE_DELETE: // delete
                conversation.removeMessage(contextMenuMessage.getMsgId());
                messageList.refresh();
                break;

            case ContextMenuActivity.RESULT_CODE_FORWARD: // forward
                // TODO 转发给联系人
//                Intent intent = new Intent(getActivity(), ForwardMessageActivity.class);
//                intent.putExtra("forward_msg_id", contextMenuMessage.getMsgId());
//                startActivity(intent);
                
                break;

            default:
                break;
            }
        }
        if(resultCode == Activity.RESULT_OK){
            switch (requestCode) {
            case REQUEST_CODE_SELECT_VIDEO: //send the video
                if (data != null) {
                    int duration = data.getIntExtra("dur", 0);
                    String videoPath = data.getStringExtra("path");
                    File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
                    try {
                        FileOutputStream fos = new FileOutputStream(file);
                        Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                        ThumbBitmap.compress(CompressFormat.JPEG, 100, fos);
                        fos.close();
                        sendVideoMessage(videoPath, file.getAbsolutePath(), duration);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case REQUEST_CODE_SELECT_FILE: //send the file
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        sendFileByUri(uri);
                    }
                }
                break;
            case REQUEST_CODE_SELECT_AT_USER:
                if(data != null){
                    String username = data.getStringExtra("username");
                    inputAtUsername(username, false);
                }
                break;
            //red packet code : 发送红包消息到聊天界面
                // TODO   //red packet code : 发送红包消息到聊天界面
            case REQUEST_CODE_SEND_RED_PACKET:
                if (data != null){
//                    sendMessage(RedPacketUtil.createRPMessage(getActivity(), data, toChatUsername));
                    LogUtils.e(getActivity(),"创建红包的发送消息","");
                    sendMessage(RedPacketUtil.createRPMessage(getActivity(), data, toChatUsername));
                }
                break;
            //end of red packet code
            default:
                break;
            }
        }
        
    }
    
    @Override
    public void onSetMessageAttributes(EMMessage message) {
        if(isRobot){
            //set message extension
            message.setAttribute("em_robot_message", isRobot);
        }
    }
    
    @Override
    public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
        return new CustomChatRowProvider();
    }
  

    @Override
    public void onEnterToChatDetails() {
        if (chatType == Constant.CHATTYPE_GROUP) {
            EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
            if (group == null) {
                Toast.makeText(getActivity(), R.string.gorup_not_found, Toast.LENGTH_SHORT).show();
                return;
            }
            startActivityForResult(
//                    (new Intent(getActivity(), GroupDetailsActivity.class).putExtra("groupId", toChatUsername)),
//                    REQUEST_CODE_GROUP_DETAIL);
                    (new Intent(getActivity(), GroupMemberListActivity.class).putExtra("groupId", toChatUsername)),
                    REQUEST_CODE_GROUP_DETAIL);

        }else if(chatType == Constant.CHATTYPE_CHATROOM){
           startActivityForResult(new Intent(getActivity(), ChatRoomDetailsActivity.class).putExtra("roomId", toChatUsername), REQUEST_CODE_GROUP_DETAIL);
        }
    }

    @Override
    public void onAvatarClick(String username) {
        //handling when user click avatar
        Intent intent = new Intent(getActivity(), UserProfileActivity.class);
        intent.putExtra("username", username);
        startActivity(intent);
    }
    
    @Override
    public void onAvatarLongClick(String username) {
        inputAtUsername(username);
    }
    
    
    @Override
    public boolean onMessageBubbleClick(EMMessage message) {
        //消息框点击事件,demo这里不做覆盖,如需覆盖,return true
        //red packet code : 拆红包页面
        // TODO   red packet code : 拆红包页面   消息框点击事件,demo这里不做覆盖,如需覆盖,return true
        if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)){
//            RedPacketUtil.openRedPacket(getActivity(), chatType, message, toChatUsername, messageList);
            LogUtils.e(getActivity(),"点击了红包","");
            return true;
        }
        //end of red packet code
        return false;
    }
    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        //red packet code : 处理红包回执透传消息
        // TODO    处理红包回执透传消息
        for (EMMessage message : messages) {
            EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
            String action = cmdMsgBody.action();//获取自定义action
            if (action.equals(RedPacketConstant.REFRESH_GROUP_RED_PACKET_ACTION)){
//                RedPacketUtil.receiveRedPacketAckMessage(message);
                LogUtils.e(getActivity(),"处理了红包的回执消息","");
                messageList.refresh();
            }
        }
        //end of red packet code
        super.onCmdMessageReceived(messages);
    }

    @Override
    public void onMessageBubbleLongClick(EMMessage message) {
       // no message forward when in chat room
        // TODO 处理聊天消息的长按事件
//        startActivityForResult((new Intent(getActivity(), ContextMenuActivity.class)).putExtra("message",message)
//                .putExtra("ischatroom", chatType == EaseConstant.CHATTYPE_CHATROOM),
//                REQUEST_CODE_CONTEXT_MENU);
    }

    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
        switch (itemId) {
        case ITEM_VIDEO:
            Intent intent = new Intent(getActivity(), ImageGridActivity.class);
            startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
            break;
        case ITEM_FILE: //file
            selectFileFromLocal();
            break;
        case ITEM_VOICE_CALL:
//            startVoiceCall();
            MPermissions.requestPermissions(this, 1,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.MODIFY_AUDIO_SETTINGS
            );

            break;
        case ITEM_VIDEO_CALL:
            startVideoCall();
            break;
        //red packet code : 进入发红包页面
        case ITEM_RED_PACKET:
            // TODO  进入发红包页面
//            RedPacketUtil.startRedPacketActivityForResult(this, chatType, toChatUsername, REQUEST_CODE_SEND_RED_PACKET);
//            ActivityUtils.jumpToActivity(getActivity(),RedPickage.class,null);
            // 请求码  是   100
            Intent intentRed = new Intent(getActivity(),RedPickage.class);
            LogUtils.e(getActivity(),"群组id",toChatUsername);
            intentRed.putExtra("group_id",toChatUsername);
            startActivityForResult(intentRed,REQUEST_CODE_SEND_RED_PACKET);
            break;
        //end of red packet code
        default:
            break;
        }
        //keep exist extend menu
        return false;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    @PermissionGrant(1)
    public void requestSdcardSuccess()
    {
        startVoiceCall();
//        Toast.makeText(getActivity(), "GRANT ACCESS SDCARD!", Toast.LENGTH_SHORT).show();
    }

    @PermissionDenied(1)
    public void requestSdcardFailed()
    {
        Toast.makeText(getActivity(), "DENY ACCESS SDCARD!", Toast.LENGTH_SHORT).show();
    }
    
    /**
     * select file
     */
    protected void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) { //api 19 and later, we can't use this way, demo just select from images
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }
    
    /**
     * make a voice call
     */
    protected void startVoiceCall() {
        if (!EMClient.getInstance().isConnected()) {
            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
        } else {
            startActivity(new Intent(getActivity(), VoiceCallActivity.class).putExtra("username", toChatUsername)
                    .putExtra("isComingCall", false));
            // voiceCallBtn.setEnabled(false);
            inputMenu.hideExtendMenuContainer();
        }
    }
    
    /**
     * make a video call
     */
    protected void startVideoCall() {
        if (!EMClient.getInstance().isConnected())
            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
        else {
            startActivity(new Intent(getActivity(), VideoCallActivity.class).putExtra("username", toChatUsername)
                    .putExtra("isComingCall", false));
            // videoCallBtn.setEnabled(false);
            inputMenu.hideExtendMenuContainer();
        }
    }
    
    /**
     * chat row provider 
     *
     */
    private final class CustomChatRowProvider implements EaseCustomChatRowProvider {
        @Override
        public int getCustomChatRowTypeCount() {
            //here the number is the message type in EMMessage::Type
           //which is used to count the number of different chat row
            return 8;
        }

        @Override
        public int getCustomChatRowType(EMMessage message) {
            if(message.getType() == EMMessage.Type.TXT){
                //voice call
                if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)){
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE_CALL : MESSAGE_TYPE_SENT_VOICE_CALL;
                }else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false)){
                    //video call
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO_CALL : MESSAGE_TYPE_SENT_VIDEO_CALL;
                }
                //red packet code : 红包消息和红包回执消息的chat row type
                // TODO 红包消息和 红包回执消息  的 row type
                else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {
                    //发送红包消息
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_RED_PACKET : MESSAGE_TYPE_SEND_RED_PACKET;
                } else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {
                    //领取红包消息
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_RED_PACKET_ACK : MESSAGE_TYPE_SEND_RED_PACKET_ACK;
                }
//                else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {
////                    //发送红包消息
//                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_RED_PACKET : MESSAGE_TYPE_SEND_RED_PACKET;
//                } else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {
////                    //领取红包消息
//                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_RED_PACKET_ACK : MESSAGE_TYPE_SEND_RED_PACKET_ACK;
//                }
                //end of red packet code
            }
            return 0;
        }

        @Override
        public EaseChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
            if(message.getType() == EMMessage.Type.TXT){
                // voice call or video call
                if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false) ||
                    message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false)){
                    return new ChatRowVoiceCall(getActivity(), message, position, adapter);
                }
                //red packet code : 红包消息和红包回执消息的chat row
                // TODO 红包消息和 红包回执消息  的 row type 2
                else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {//发送红包消息
                    return new ChatRowRedPacket(getActivity(), message, position, adapter);
                } else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {//open redpacket message
                    return new ChatRowRedPacketAck(getActivity(), message, position, adapter);
                }
//                else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {//发送红包消息
//                    return new ChatRowRedPacket(getActivity(), message, position, adapter);
//                } else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {//open redpacket message
//                    return new ChatRowRedPacketAck(getActivity(), message, position, adapter);
//                }
                //end of red packet code
            }
            return null;
        }

    }

}

关于环信中  昵称和头像的处理:

        个人感觉官网文档中的 理解起来稍微复杂 而且还需要仔细去看环信的代码,所以就自己搞了个简单的 进行了实现

1. 在easeui库里面 创建数据库及表(用来存 环信登录帐号 及 服务器返回的好友帐号及对应的昵称 和 头像的 url )

2. 在对应要展示的时候  从数据库取出对应的信息 对控件进行赋值

例如: 我的是群聊,而在聊天界面会出现 群组里的所有成员,默认是显示的环信帐号 而不是 显示的昵称    下面有的我界面

可以在  群组列表的时候 服务器返回  群组成员信息  进行保存到数据库   在聊天界面进行 取值



关于聊天时    收到消息       让列表显示小红点或提示信息 的处理:

在 群组列表界面  增加了监听   

//收到消息
//收到透传消息
//收到已读回执
//收到已送达回执
//消息状态变动
        msgListener = new EMMessageListener() {

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                //收到消息
                LogUtils.e(mContext,"onMessageReceived","触发了");
//                listView.smoothScrollBy(1,0);
                messageList = EaseChatFragment.getMessageList();
                if (messageList!=null){
                    for (EMMessage message : messages) {
                        String username = null;
                        // group message
                        if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                            username = message.getTo();
                        } else {
                            // single chat message
                            username = message.getFrom();
                        }

                        // if the message is for current conversation
                        if (username.equals(EaseChatFragment.getToChatUsername())) {
                            messageList.refreshSelectLast();
                            EaseUI.getInstance().getNotifier().vibrateAndPlayTone(message);
                            Log.e("聊天界面收到消息的监听","震动并加声音");
                        } else {
                            EaseUI.getInstance().getNotifier().onNewMsg(message);
                            Log.e("聊天界面收到消息的监听","新消息");
                        }
                    }
                }
                listView.getRefreshableView().smoothScrollBy(1,0);
                groupAdapter.notifyDataSetChanged();
                LogUtils.e(mContext,"onMessageReceived","触发了2");
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                //收到透传消息
            }

            @Override
            public void onMessageReadAckReceived(List<EMMessage> messages) {
                //收到已读回执
            }

            @Override
            public void onMessageDeliveryAckReceived(List<EMMessage> message) {
                //收到已送达回执
            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
                //消息状态变动
            }
        };
        EMClient.getInstance().chatManager().addMessageListener(msgListener);



然后修改了 easeui里面的一丢丢代码:




2017.01.10修改:

     







2017.01.10 update end.

2017.01.12 update start:

  为了  android 和  ios 的共通,代码又做了 略微的修改:






2017.01.12 update end.





版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

第一次记录问题, 集成环信easeui库的地图问题

关于在环信集成easeui库的时候使用百度地图出现的问题 : 问题描述 : 集成easeui库使用默认的百度地图,点击地图会白屏,然后退回上个界面 (大部分手机没有问题, 极少部分手机有问题...
  • zzh1026
  • zzh1026
  • 2016年05月05日 16:25
  • 1775

环信 easeui导入 问题

环信的 easeui导入遇到的一些问题

记一次导入环信聊天demo的过程

1,下载sdk:环新官网:[环新官网](http://www.easemob.com/download/im) 下载sdk 目录结构:**doc文件夹:SDK相关API文档examples文件夹:C...

环信即时通信聊天理解

使用环境:在获取会话列表之后,就可以收集到两个数据,聊天的类型和聊天的对象。 携带这两个参数跳转到聊天的ChatActivity之后,这哥Activity中就布局只是设置了一个占位FrameLayou...

利用环信集成聊天所遇到的坑以及解决的办法

环信开发中遇到的坑

前端+后台,看技术大大如何实现环信集成!

开发者分享的环信DEMO,包括(前端+后台),前端集成了环信SDK,后台提供了与环信服务器集成的源码方案。技术大神如此给力,小编给跪了! 以下为前端页面详情介绍: 本DEMO调用appca...

环信集成全过程有demo

前言:普通的应用中一般只用到传输文件,发送文字图片信息,所以此处不做语音视频通讯的集成,够用就行 1.准备工作 2.注册,登录 3.联系人列表开发 4.聊天界面开发 5.设置界面开发 6.添加,接受好...

关于使用环信web-im实现登录(直接登录)

本来没想发教程的,不过好像目前还是有很多小白为此困扰,并且网上关于这方面的资料的确比较少,小白很难入门。刚好收到人的求助,就发了个,给小白看的。...

集成环信遇到的相关问题整理

2. iOS SDK 从低版本

环信扩展消息

android扩展消息(名片集成) 很多社交软件都少不了名片这种东西,可是,用环信怎么去解决这个名片问题呢。 首先呢,大家要注意环信IOS版的扩展消息ext不能接收json格式数据...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:环信聊天的基本集成步骤及遇到的问题
举报原因:
原因补充:

(最多只允许输入30个字)