还原问题:
如图主Ui是activity,下侧的围观区是Fragment,根据环信的demo,上面聊天区可以正常刷新UI。
但是围观区数据源变化,但是不能刷新UI。
思路:
研究一个下午,理了好久逻辑。发现我的问题是:
chatActivity的事件监听(接收新消息),是通知activity的列表更新(上侧),但是没有通知围观区的列表更新。
解决办法:
在监听事件中通知围观区更新数据
下面附上我的代码:
这是主UI activity
package com.example.administrator.bazipaipan.chat;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.easemob.EMChatRoomChangeListener;
import com.easemob.EMError;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatRoom;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.LocationMessageBody;
import com.easemob.chat.NormalFileMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VideoMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.EMLog;
import com.easemob.util.PathUtil;
import com.easemob.util.VoiceRecorder;
import com.example.administrator.bazipaipan.BaseActivity;
import com.example.administrator.bazipaipan.MyApplication;
import com.example.administrator.bazipaipan.R;
import com.example.administrator.bazipaipan.chat.dialogActivity.AugurBackDialogActivity;
import com.example.administrator.bazipaipan.chat.fragment.ChatContributeFragment;
import com.example.administrator.bazipaipan.chat.fragment.ChatHistoryFragment;
import com.example.administrator.bazipaipan.chat.fragment.ChatLookerFragment;
import com.example.administrator.bazipaipan.chat.fragment.ChatQueueFragment;
import com.example.administrator.bazipaipan.chat.huanxin.DemoHXSDKHelper;
import com.example.administrator.bazipaipan.chat.huanxin.activity.AlertDialog;
import com.example.administrator.bazipaipan.chat.huanxin.activity.BaiduMapActivity;
import com.example.administrator.bazipaipan.chat.huanxin.adapter.ExpressionAdapter;
import com.example.administrator.bazipaipan.chat.huanxin.adapter.ExpressionPagerAdapter;
import com.example.administrator.bazipaipan.chat.huanxin.adapter.MessageAdapter;
import com.example.administrator.bazipaipan.chat.huanxin.adapter.VoicePlayClickListener;
import com.example.administrator.bazipaipan.chat.huanxin.applib.controller.HXSDKHelper;
import com.example.administrator.bazipaipan.chat.huanxin.utils.CommonUtils;
import com.example.administrator.bazipaipan.chat.huanxin.utils.ImageUtils;
import com.example.administrator.bazipaipan.chat.huanxin.utils.SmileUtils;
import com.example.administrator.bazipaipan.chat.huanxin.widget.ExpandGridView;
import com.example.administrator.bazipaipan.chat.huanxin.widget.PasteEditText;
import com.example.administrator.bazipaipan.chat.receiver.NewMessageBroadcastReceiver;
import com.example.administrator.bazipaipan.login.model.MyUser;
import com.example.administrator.bazipaipan.utils.BmobUtils;
import com.example.administrator.bazipaipan.widget.VerticalSwipeRefreshLayout;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.UpdateListener;
/**
* Created by 王中阳 on 2015/12/25.
*/
public class ChatContainerActivity extends BaseActivity implements TabLayout.OnTabSelectedListener, View.OnClickListener, EMEventListener, TextView.OnEditorActionListener {
public static final String TAG = “ChatContainerActivity”;
private ChatContainerActivity mycontext;
//自定义测试
private TabLayout mTabLayout;
private ViewPager mViewPager;
private List mTitleList = new ArrayList<>();//页卡标题集合
private List mFragmentList = new ArrayList<>();//页卡视图集合
private ChatLookerFragment chatLookerFragment;
private ChatQueueFragment chatQueueFragment;
private ChatContributeFragment chatContributeFragment;
//actionbar相关
ActionBar ab;
//聊天列表
private VerticalSwipeRefreshLayout mSwipeLayout;
//控件
private LinearLayout chatmain_container_focusnum_sel, chatmain_container_focusnum;
private TextView tv_chatmain_focusnum, tv_chatmain_focusnum_sel;
//测算历史
private ChatHistoryFragment chatHistoryFragment;
private FrameLayout fl_container_chatmain_history;
private MenuItem item;
//下部围观区整体
private LinearLayout ll_container_allbottom;
//单聊逻辑
//控件
private EditText et_chatlooker_input;
//发送给谁 大师或者是命主 非游客身份
NewMessageBroadcastReceiver msgReceiver;
boolean isfirst;
//聊天输入框总容器
LinearLayout chatlooker_container_inputall;
// chatdemo up
private static final int REQUEST_CODE_EMPTY_HISTORY = 2;
public static final int REQUEST_CODE_CONTEXT_MENU = 3;
private static final int REQUEST_CODE_MAP = 4;
public static final int REQUEST_CODE_TEXT = 5;
public static final int REQUEST_CODE_VOICE = 6;
public static final int REQUEST_CODE_PICTURE = 7;
public static final int REQUEST_CODE_LOCATION = 8;
public static final int REQUEST_CODE_NET_DISK = 9;
public static final int REQUEST_CODE_FILE = 10;
public static final int REQUEST_CODE_COPY_AND_PASTE = 11;
public static final int REQUEST_CODE_PICK_VIDEO = 12;
public static final int REQUEST_CODE_DOWNLOAD_VIDEO = 13;
public static final int REQUEST_CODE_VIDEO = 14;
public static final int REQUEST_CODE_DOWNLOAD_VOICE = 15;
public static final int REQUEST_CODE_SELECT_USER_CARD = 16;
public static final int REQUEST_CODE_SEND_USER_CARD = 17;
public static final int REQUEST_CODE_CAMERA = 18;
public static final int REQUEST_CODE_LOCAL = 19;
public static final int REQUEST_CODE_CLICK_DESTORY_IMG = 20;
public static final int REQUEST_CODE_GROUP_DETAIL = 21;
public static final int REQUEST_CODE_SELECT_VIDEO = 23;
public static final int REQUEST_CODE_SELECT_FILE = 24;
public static final int REQUEST_CODE_ADD_TO_BLACKLIST = 25;
public static final int RESULT_CODE_COPY = 1;
public static final int RESULT_CODE_DELETE = 2;
public static final int RESULT_CODE_FORWARD = 3;
public static final int RESULT_CODE_OPEN = 4;
public static final int RESULT_CODE_DWONLOAD = 5;
public static final int RESULT_CODE_TO_CLOUD = 6;
public static final int RESULT_CODE_EXIT_GROUP = 7;
public static final int CHATTYPE_SINGLE = 1;
public static final int CHATTYPE_GROUP = 2;
public static final int CHATTYPE_CHATROOM = 3;
//roomid 1测算 2围观区
public static String roomID1; //1是测算群
public static String roomID2; // 2是围观群
public static String AUGURID; // 2是围观群
public static final String COPY_IMAGE = "EASEMOBIMG";
private View recordingContainer;
private ImageView micImage;
private TextView recordingHint;
private ListView listView;
private PasteEditText etinput_talkaugur;
private View buttonSetModeKeyboard;
private View buttonSetModeVoice;
// private View buttonSend;
private View buttonPressToSpeak;
// private ViewPager expressionViewpager;
private LinearLayout emojiIconContainer;
private LinearLayout btnContainer;
private ImageView locationImgview;
private View more;
private int position;
private ClipboardManager clipboard;
private ViewPager expressionViewpager;
private InputMethodManager manager;
private List reslist;
private Drawable[] micImages;
private int chatType = 2;
private EMConversation conversation;
public static ChatContainerActivity activityInstance = null;
// 给谁发送消息
private String toChatUsername;
private VoiceRecorder voiceRecorder;
private MessageAdapter adapter;
private File cameraFile;
static int resendPos;
private ImageView iv_emoticons_normal;
private ImageView iv_emoticons_checked;
private RelativeLayout edittext_layout;
private ProgressBar loadmorePB;
private boolean isloading;
private final int pagesize = 20;
private boolean haveMoreData = true;
private ImageView btnMore;
public String playMsgId;
private SwipeRefreshLayout swipeRefreshLayout;
private Handler micImageHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
// 切换msg切换图片
micImage.setImageDrawable(micImages[msg.what]);
}
};
public EMGroup group;
public EMChatRoom room;
public boolean isRobot;
//语音键盘的切换显示
RelativeLayout notvoice_contaier;
//围观区输入键盘
LinearLayout container_chatlooker_talkall, container_chatlooker_talkaugur;
String usertype = "0"; //用户身份 0围观区游客 1排队 2大师 3命主 从bmob表中获取
public static final String YOUKE = "0";
public static final String QUEUE = "1";
public static final String AUGUR = "2";
public static final String MINGZHU = "3";
public static final String OWNER = "4"; //群聊的群主
boolean isRoomOwner = true;
// chatdemo down
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mychat);
ButterKnife.bind(this);
mycontext = this;
initRoomid();
initviews();
setUpView();
//进入2个群聊,先进入到围观的Fragment(非大师)大师进入
chatLogic(); //根据owner判断
//1从bmob中更新数据 先缓存在更新
getCurrentType(); //根据type 判断
}
private void initRoomid() {
// 判断单聊还是群聊
Bundle bundle = ChatContainerActivity.this.getIntent().getBundleExtra("bundle");
if (bundle == null) {
this.log("bundle" + bundle.toString());
return;
}
roomID1 = bundle.getString("roomID1");
roomID2 = bundle.getString("roomID2");
AUGURID = bundle.getString("AUGURID");
MyApplication.getInstance().setRoomID2(roomID2);
MyApplication.getInstance().setAUGURID(AUGURID);
}
private void chatLogic() {
if (getRoomOwner()) {
chatlooker_container_inputall.setVisibility(View.VISIBLE);
} else {
chatlooker_container_inputall.setVisibility(View.GONE);
}
}
//获得当前房间的群主
private boolean getRoomOwner() {
//根据群聊ID从服务器获取群聊基本信息
new Thread(new Runnable() {
@Override
public void run() {
EMGroup group = null;
try {
group = EMGroupManager.getInstance().getGroupFromServer(roomID1);
//保存获取下来的群聊基本信息
// EMGroupManager.getInstance().createOrUpdateLocalGroup(group);
group.getMembers();//获取群成员
String owner = group.getOwner();//获取当前群主
//把房主id贡献给全局
MyApplication.getInstance().setOwnerId(owner);
String currentUser = EMChatManager.getInstance().getCurrentUser();
if (owner.equals(currentUser)) {
usertype = OWNER;
isRoomOwner = true;
} else {
isRoomOwner = false;
}
} catch (EaseMobException e) {
e.printStackTrace();
}
}
}).start();
return isRoomOwner;
}
//获得当前user的type
private void getCurrentType() {
BmobQuery bmobQuery = new BmobQuery<>();
bmobQuery.getObject(this, BmobUtils.getCurrentId(mycontext), new GetListener() {
@Override
public void onSuccess(MyUser myUser) {
usertype = myUser.getType();
}
@Override
public void onFailure(int i, String s) {
log("chatcontainerActivity 查询type:" + s);
}
});
switch (usertype) {
//自己的房间
case OWNER:
// container_chatlooker_talkall.setVisibility(View.GONE);
// container_chatlooker_talkaugur.setVisibility(View.VISIBLE);
// chatlooker_container_inputall.setVisibility(View.VISIBLE);
break;
case MINGZHU:
chatlooker_container_inputall.setVisibility(View.VISIBLE);
break;
case YOUKE:
// container_chatlooker_talkall.setVisibility(View.VISIBLE);
// container_chatlooker_talkaugur.setVisibility(View.GONE);
//隐藏掉当前的全键盘
chatlooker_container_inputall.setVisibility(View.GONE);
break;
default:
// container_chatlooker_talkall.setVisibility(View.VISIBLE);
// container_chatlooker_talkaugur.setVisibility(View.GONE);
//隐藏掉当前的全键盘
chatlooker_container_inputall.setVisibility(View.GONE);
break;
}
}
//更新当前user的type
private void updateType(final String newType) {
String cuid = BmobUtils.getCurrentId(mycontext);
MyUser myUser = new MyUser();
myUser.setType(newType);
myUser.update(mycontext, cuid, new UpdateListener() {
@Override
public void onSuccess() {
if (newType.equals("0")) {
toast("回到围观区");
} else if (newType.equals("1")) {
toast("排队成功");
} else if (newType.equals("2")) {
toast("大师进入房间啦");
} else if (newType.equals("3")) {
toast("轮到您和大师算卦啦");
}
}
@Override
public void onFailure(int i, String s) {
}
});
}
private void setUpView() {
iv_emoticons_normal.setOnClickListener(this);
iv_emoticons_checked.setOnClickListener(this);
// position = getIntent().getIntExtra("position", -1);
clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
// 判断单聊还是群聊
Bundle bundle = ChatContainerActivity.this.getIntent().getBundleExtra("bundle");
if (bundle == null) {
this.log("bundle" + bundle.toString());
return;
}
chatType = Integer.valueOf(bundle.getString("chatType"));
log("chatType" + chatType);
//群聊
toChatUsername = bundle.getString("roomID1");
roomID2 = bundle.getString("roomID1");
log("toChatUsername" + toChatUsername);
if (chatType == CHATTYPE_SINGLE) { // 单聊
// toChatUsername = getIntent().getStringExtra(“userId”);
} else {
findViewById(R.id.container_voice_call).setVisibility(View.GONE);
findViewById(R.id.container_video_call).setVisibility(View.GONE); //视频通话不需要
if (chatType == CHATTYPE_GROUP) {
onGroupViewCreation();
} else {
onChatRoomViewCreation();
}
}
// for chatroom type, we only init conversation and create view adapter on success
if (chatType != CHATTYPE_CHATROOM) {
onConversationInit();
onListViewCreation();
// show forward message if the message is not null
String forward_msg_id = getIntent().getStringExtra("forward_msg_id");
if (forward_msg_id != null) {
// 显示发送要转发的消息
forwardMessage(forward_msg_id);
}
}
}
private void forwardMessage(String forward_msg_id) {
final EMMessage forward_msg = EMChatManager.getInstance().getMessage(forward_msg_id);
EMMessage.Type type = forward_msg.getType();
switch (type) {
case TXT:
// 获取消息内容,发送消息
String content = ((TextMessageBody) forward_msg.getBody()).getMessage();
sendText(content);
break;
case IMAGE:
// 发送图片
String filePath = ((ImageMessageBody) forward_msg.getBody()).getLocalUrl();
if (filePath != null) {
File file = new File(filePath);
if (!file.exists()) {
// 不存在大图发送缩略图
filePath = ImageUtils.getThumbnailImagePath(filePath);
}
sendPicture(filePath);
}
break;
default:
break;
}
if (forward_msg.getChatType() == EMMessage.ChatType.ChatRoom) {
EMChatManager.getInstance().leaveChatRoom(forward_msg.getTo());
}
}
private void onListViewCreation() {
adapter = new MessageAdapter(mycontext, toChatUsername, chatType);
// 显示消息
listView.setAdapter(adapter);
listView.setOnScrollListener(new ListScrollListener());
adapter.refreshSelectLast();
listView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideKeyboard();
more.setVisibility(View.GONE);
iv_emoticons_normal.setVisibility(View.VISIBLE);
iv_emoticons_checked.setVisibility(View.INVISIBLE);
emojiIconContainer.setVisibility(View.GONE);
btnContainer.setVisibility(View.GONE);
return false;
}
});
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
switch (v.getId()) {
//发送到测算区
case R.id.etinput_talkaugur:
//监听键盘发送功能
String sendmsg;
sendmsg = etinput_talkaugur.getText().toString().trim();
if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
if (TextUtils.isEmpty(sendmsg)) {
return false;
} else {
String s = etinput_talkaugur.getText().toString();
sendText(s);
}
return true;
}
break;
}
return false;
}
/**
* listview滑动监听listener
*/
private class ListScrollListener implements AbsListView.OnScrollListener {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
if (view.getFirstVisiblePosition() == 0 && !isloading && haveMoreData && conversation.getAllMessages().size() != 0) {
isloading = true;
loadmorePB.setVisibility(View.VISIBLE);
// sdk初始化加载的聊天记录为20条,到顶时去db里获取更多
List messages;
EMMessage firstMsg = conversation.getAllMessages().get(0);
try {
// 获取更多messges,调用此方法的时候从db获取的messages
// sdk会自动存入到此conversation中
if (chatType == CHATTYPE_SINGLE)
messages = conversation.loadMoreMsgFromDB(firstMsg.getMsgId(), pagesize);
else
messages = conversation.loadMoreGroupMsgFromDB(firstMsg.getMsgId(), pagesize);
} catch (Exception e1) {
loadmorePB.setVisibility(View.GONE);
return;
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
}
if (messages.size() != 0) {
// 刷新ui
if (messages.size() > 0) {
adapter.refreshSeekTo(messages.size() - 1);
}
if (messages.size() != pagesize)
haveMoreData = false;
} else {
haveMoreData = false;
}
loadmorePB.setVisibility(View.GONE);
isloading = false;
}
break;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
}
protected void onConversationInit() {
if (chatType == CHATTYPE_SINGLE) {
} else if (chatType == CHATTYPE_GROUP) {
conversation = EMChatManager.getInstance().getConversationByType(toChatUsername, EMConversation.EMConversationType.GroupChat);
} else if (chatType == CHATTYPE_CHATROOM) {
}
// 把此会话的未读数置为0
conversation.markAllMessagesAsRead();
// 初始化db时,每个conversation加载数目是getChatOptions().getNumberOfMessagesLoaded
// 这个数目如果比用户期望进入会话界面时显示的个数不一样,就多加载一些
final List msgs = conversation.getAllMessages();
int msgCount = msgs != null ? msgs.size() : 0;
if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
String msgId = null;
if (msgs != null && msgs.size() > 0) {
msgId = msgs.get(0).getMsgId();
}
if (chatType == CHATTYPE_SINGLE) {
conversation.loadMoreMsgFromDB(msgId, pagesize);
} else {
conversation.loadMoreGroupMsgFromDB(msgId, pagesize);
}
}
EMChatManager.getInstance().addChatRoomChangeListener(new EMChatRoomChangeListener() {
@Override
public void onChatRoomDestroyed(String roomId, String roomName) {
if (roomId.equals(toChatUsername)) {
finish();
}
}
@Override
public void onMemberJoined(String roomId, String participant) {
}
@Override
public void onMemberExited(String roomId, String roomName,
String participant) {
}
@Override
public void onMemberKicked(String roomId, String roomName,
String participant) {
if (roomId.equals(toChatUsername)) {
String curUser = EMChatManager.getInstance().getCurrentUser();
if (curUser.equals(participant)) {
EMChatManager.getInstance().leaveChatRoom(toChatUsername);
finish();
}
}
}
});
}
//----------以下是actionbar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_chat, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
chatHistoryFragment = new ChatHistoryFragment();
FragmentManager fm = getSupportFragmentManager();
switch (item.getItemId()) {
case R.id.action_bagua:
break;
case R.id.action_history:
fm.beginTransaction().add(R.id.fl_container_chatmain_history, chatHistoryFragment).commit();
break;
case R.id.action_share:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "http://www.up1024.com/");
sendIntent.setType("text/plain");
startActivity(sendIntent);
break;
//back键退出
case android.R.id.home:
// finish();
Intent intent = new Intent(mycontext, AugurBackDialogActivity.class);
mycontext.startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
//———以上是actionbar
private void initviews() {
// chatdemo up
//测算区
//最外层输入框
chatlooker_container_inputall = (LinearLayout) findViewById(R.id.chatlooker_container_inputall);
container_chatlooker_talkaugur = (LinearLayout) findViewById(R.id.container_chatlooker_talkaugur);
recordingContainer = findViewById(R.id.recording_container);
micImage = (ImageView) findViewById(R.id.mic_image);
recordingHint = (TextView) findViewById(R.id.recording_hint);
listView = (ListView) findViewById(R.id.rv_chat_list); //显示聊天记录
etinput_talkaugur = (PasteEditText) findViewById(R.id.etinput_talkaugur); //对话大师输入框
//消息键盘 和语音键盘的切换
buttonSetModeKeyboard = findViewById(R.id.btn_set_mode_keyboard);
notvoice_contaier = (RelativeLayout) findViewById(R.id.edittext_layout);
edittext_layout = (RelativeLayout) findViewById(R.id.notvoice_contaier); //发送消息框的容器
buttonSetModeVoice = findViewById(R.id.iv_chatlooker_voice);//语音键盘
buttonPressToSpeak = findViewById(R.id.btn_press_to_speak);
expressionViewpager = (ViewPager) findViewById(R.id.vPager); //表情翻页
emojiIconContainer = (LinearLayout) findViewById(R.id.ll_face_container); //emoji表情包容器
btnContainer = (LinearLayout) findViewById(R.id.ll_btn_container); //图片 语音按钮等
locationImgview = (ImageView) findViewById(R.id.btn_location); //位置按钮
iv_emoticons_normal = (ImageView) findViewById(R.id.iv_emoticons_normal); //表情按钮
iv_emoticons_checked = (ImageView) findViewById(R.id.iv_emoticons_checked); //按下表情按钮
loadmorePB = (ProgressBar) findViewById(R.id.pb_load_more); //加载聊天的进度条
btnMore = (ImageView) findViewById(R.id.btn_more); //发送图片 位置等的按钮
iv_emoticons_normal.setVisibility(View.VISIBLE); //表情
iv_emoticons_checked.setVisibility(View.INVISIBLE); //表情
more = findViewById(R.id.more); //底部导航条
voiceCallBtn = (ImageView) findViewById(R.id.btn_voice_call);
videoCallBtn = (ImageView) findViewById(R.id.btn_video_call);
// 动画资源文件,用于录制语音时
micImages = new Drawable[]{getResources().getDrawable(R.drawable.record_animate_01),
getResources().getDrawable(R.drawable.record_animate_02),
getResources().getDrawable(R.drawable.record_animate_03),
getResources().getDrawable(R.drawable.record_animate_04),
getResources().getDrawable(R.drawable.record_animate_05),
getResources().getDrawable(R.drawable.record_animate_06),
getResources().getDrawable(R.drawable.record_animate_07),
getResources().getDrawable(R.drawable.record_animate_08),
getResources().getDrawable(R.drawable.record_animate_09),
getResources().getDrawable(R.drawable.record_animate_10),
getResources().getDrawable(R.drawable.record_animate_11),
getResources().getDrawable(R.drawable.record_animate_12),
getResources().getDrawable(R.drawable.record_animate_13),
getResources().getDrawable(R.drawable.record_animate_14)};
// 表情list
reslist = getExpressionRes(35);
// 初始化表情viewpager
List views = new ArrayList();
View gv1 = getGridChildView(1);
View gv2 = getGridChildView(2);
views.add(gv1);
views.add(gv2);
expressionViewpager.setAdapter(new ExpressionPagerAdapter(views));
edittext_layout.requestFocus();
voiceRecorder = new VoiceRecorder(micImageHandler);
buttonPressToSpeak.setOnTouchListener(new PressToSpeakListen());
etinput_talkaugur.setOnEditorActionListener(this);
etinput_talkaugur.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
// edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_active);
} else {
// edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_normal);
}
}
});
etinput_talkaugur.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_active);
more.setVisibility(View.GONE);
// iv_emoticons_normal.setVisibility(View.VISIBLE);
// iv_emoticons_checked.setVisibility(View.INVISIBLE);
emojiIconContainer.setVisibility(View.GONE);
btnContainer.setVisibility(View.GONE);
}
});
// 监听文字框
etinput_talkaugur.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!TextUtils.isEmpty(s)) {
// btnMore.setVisibility(View.GONE);
// buttonSend.setVisibility(View.VISIBLE);
} else {
// btnMore.setVisibility(View.VISIBLE);
// buttonSend.setVisibility(View.GONE);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
//刷新列表 聊天的列表
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.chat_swipe_layout);
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
android.R.color.holo_orange_light, android.R.color.holo_red_light);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (listView.getFirstVisiblePosition() == 0 && !isloading && haveMoreData) {
List messages;
try {
if (chatType == CHATTYPE_SINGLE) {
messages = conversation.loadMoreMsgFromDB(adapter.getItem(0).getMsgId(), pagesize);
} else {
messages = conversation.loadMoreGroupMsgFromDB(adapter.getItem(0).getMsgId(), pagesize);
}
} catch (Exception e1) {
swipeRefreshLayout.setRefreshing(false);
return;
}
if (messages.size() > 0) {
adapter.notifyDataSetChanged();
adapter.refreshSeekTo(messages.size() - 1);
if (messages.size() != pagesize) {
haveMoreData = false;
}
} else {
haveMoreData = false;
}
isloading = false;
} else {
Toast.makeText(ChatContainerActivity.this, getResources().getString(R.string.no_more_messages), Toast.LENGTH_SHORT).show();
}
swipeRefreshLayout.setRefreshing(false);
}
}, 1000);
}
});
// chatdemo down
//测算历史
fl_container_chatmain_history = (FrameLayout) findViewById(R.id.fl_container_chatmain_history);
//围观区整体
ll_container_allbottom = (LinearLayout) findViewById(R.id.ll_container_allbottom);
ll_container_allbottom.setOnClickListener(this);
//关注切换
chatmain_container_focusnum = (LinearLayout) findViewById(R.id.chatmain_container_focusnum);
chatmain_container_focusnum.setOnClickListener(this);
chatmain_container_focusnum_sel = (LinearLayout) findViewById(R.id.chatmain_container_focusnum_sel);
chatmain_container_focusnum_sel.setOnClickListener(this);
tv_chatmain_focusnum = (TextView) findViewById(R.id.tv_chatmain_focusnum);
tv_chatmain_focusnum.setOnClickListener(this);
tv_chatmain_focusnum_sel = (TextView) findViewById(R.id.tv_chatmain_focusnum_sel);
tv_chatmain_focusnum_sel.setOnClickListener(this);
// actionbar的切换
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ab = getSupportActionBar();
if (ab != null) {
ab.setHomeAsUpIndicator(R.drawable.back);
// 给左上角图标的左边加上一个返回的图标
ab.setDisplayHomeAsUpEnabled(true);
//隐藏icon logo
ab.setDisplayShowHomeEnabled(false);
ab.setDisplayShowTitleEnabled(true);
}
//tabview及viewpager联动效果
mViewPager = (ViewPager) mycontext.findViewById(R.id.chat_vp_view);
mTabLayout = (TabLayout) mycontext.findViewById(R.id.chat_tabs);
//添加页卡视图
mFragmentList.add(chatLookerFragment);
mFragmentList.add(chatQueueFragment);
mFragmentList.add(chatContributeFragment);
//添加页卡标题
mTitleList.add("围观区");
mTitleList.add("排队");
mTitleList.add("贡献");
mTabLayout.setTabMode(TabLayout.MODE_FIXED);//设置tab模式,当前为系统默认模式
mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(0)));//添加tab选项卡
mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(1)));
mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(2)));
MyChatPagerAdapter mAdapter = new MyChatPagerAdapter(getSupportFragmentManager(), mFragmentList, mycontext);
mViewPager.setAdapter(mAdapter);//给ViewPager设置适配器
mTabLayout.setupWithViewPager(mViewPager);//将TabLayout和ViewPager关联起来。
mTabLayout.setTabsFromPagerAdapter(mAdapter);//给Tabs设置适配器
if (mViewPager != null) {
setupViewPager(mViewPager);
mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.setOnTabSelectedListener(this);
}
}
//切换 抽取
public void changeTab(int i) {
switch (i) {
case 0:
chatLookerFragment.onRefresh();
//键盘消失
chatLogic();
break;
case 1:
chatQueueFragment.onRefresh();
//键盘消失
chatlooker_container_inputall.setVisibility(View.GONE);
break;
case 2:
chatContributeFragment.onRefresh();
//键盘消失
chatlooker_container_inputall.setVisibility(View.GONE);
break;
}
}
private void setupViewPager(ViewPager viewPager) {
FragmentAdapter fragmentAdapter = new FragmentAdapter(mycontext.getSupportFragmentManager());
chatLookerFragment = new ChatLookerFragment();
fragmentAdapter.addFragment(chatLookerFragment, getString(R.string.chatlooker));
chatQueueFragment = new ChatQueueFragment();
fragmentAdapter.addFragment(chatQueueFragment, getString(R.string.chatqueue));
chatContributeFragment = new ChatContributeFragment();
fragmentAdapter.addFragment(chatContributeFragment, getString(R.string.chatcontribute));
viewPager.setAdapter(fragmentAdapter);
}
//切换
static class FragmentAdapter extends FragmentPagerAdapter {
private final List mFragments = new ArrayList<>();
private final List mFragmentTitles = new ArrayList<>();
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
//tabview点击效果
@Override
public void onTabSelected(TabLayout.Tab tab) {
int pos = tab.getPosition();
mViewPager.setCurrentItem(pos);
changeTab(pos);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
//适配器
class MyChatPagerAdapter extends FragmentPagerAdapter
{
private ChatContainerActivity activity;
private List datas;
public MyChatPagerAdapter(FragmentManager fm, List datas, ChatContainerActivity activity) {
super(fm);
this.activity = activity;
this.datas = datas;
}
@Override
public Fragment getItem(int position) {
return datas.get(position);
}
@Override
public int getCount() {
Log.e("datas", datas.size() + "");
return datas.size();
}
@Override
public CharSequence getPageTitle(int position) {
return mTitleList.get(position);//页卡标题
}
添加页卡 初始化item
@Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;//官方推荐写法
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
}
@Override
protected void onStop() {
super.onStop();
//移除之前的viewpager数据 待缓存优化
mFragmentList.clear();
}
@Override
protected void onDestroy() {
super.onDestroy();
// unregisterReceiver(msgReceiver);
}
// chatdemo 监听 up
private PowerManager.WakeLock wakeLock;
private ImageView voiceCallBtn;
private ImageView videoCallBtn;
/**
* 按住说话listener
*/
class PressToSpeakListen implements View.OnTouchListener {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (!CommonUtils.isExitsSdcard()) {
String st4 = getResources().getString(R.string.Send_voice_need_sdcard_support);
Toast.makeText(mycontext, st4, Toast.LENGTH_SHORT).show();
return false;
}
try {
v.setPressed(true);
wakeLock.acquire();
if (VoicePlayClickListener.isPlaying)
VoicePlayClickListener.currentPlayListener.stopPlayVoice();
recordingContainer.setVisibility(View.VISIBLE);
recordingHint.setText(getString(R.string.move_up_to_cancel));
recordingHint.setBackgroundColor(Color.TRANSPARENT);
voiceRecorder.startRecording(null, toChatUsername, getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
v.setPressed(false);
if (wakeLock.isHeld())
wakeLock.release();
if (voiceRecorder != null)
voiceRecorder.discardRecording();
recordingContainer.setVisibility(View.INVISIBLE);
Toast.makeText(mycontext, R.string.recoding_fail, Toast.LENGTH_SHORT).show();
return false;
}
return true;
case MotionEvent.ACTION_MOVE: {
if (event.getY() < 0) {
recordingHint.setText(getString(R.string.release_to_cancel));
recordingHint.setBackgroundResource(R.drawable.recording_text_hint_bg);
} else {
recordingHint.setText(getString(R.string.move_up_to_cancel));
recordingHint.setBackgroundColor(Color.TRANSPARENT);
}
return true;
}
case MotionEvent.ACTION_UP:
v.setPressed(false);
recordingContainer.setVisibility(View.INVISIBLE);
if (wakeLock.isHeld())
wakeLock.release();
if (event.getY() < 0) {
// discard the recorded audio.
voiceRecorder.discardRecording();
} else {
// stop recording and send voice file
String st1 = getResources().getString(R.string.Recording_without_permission);
String st2 = getResources().getString(R.string.The_recording_time_is_too_short);
String st3 = getResources().getString(R.string.send_failure_please);
try {
int length = voiceRecorder.stopRecoding();
if (length > 0) {
sendVoice(voiceRecorder.getVoiceFilePath(), voiceRecorder.getVoiceFileName(toChatUsername),
Integer.toString(length), false);
} else if (length == EMError.INVALID_FILE) {
Toast.makeText(getApplicationContext(), st1, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), st2, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(mycontext, st3, Toast.LENGTH_SHORT).show();
}
}
return true;
default:
recordingContainer.setVisibility(View.INVISIBLE);
if (voiceRecorder != null)
voiceRecorder.discardRecording();
return false;
}
}
}
/**
* 获取表情的gridview的子view
*
* @param i
* @return
*/
private View getGridChildView(int i) {
View view = View.inflate(this, R.layout.expression_gridview, null);
ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
List list = new ArrayList();
if (i == 1) {
List list1 = reslist.subList(0, 20);
list.addAll(list1);
} else if (i == 2) {
list.addAll(reslist.subList(20, reslist.size()));
}
list.add("delete_expression");
final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this, 1, list);
gv.setAdapter(expressionAdapter);
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
String filename = expressionAdapter.getItem(position);
try {
// 文字输入框可见时,才可输入表情
// 按住说话可见,不让输入表情
if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) {
if (filename != "delete_expression") { // 不是删除键,显示表情
// 这里用的反射,所以混淆的时候不要混淆SmileUtils这个类
Class clz = Class.forName("com.easemob.chatuidemo.utils.SmileUtils");
Field field = clz.getField(filename);
etinput_talkaugur.append(SmileUtils.getSmiledText(mycontext,
(String) field.get(null)));
} else { // 删除文字或者表情
if (!TextUtils.isEmpty(etinput_talkaugur.getText())) {
int selectionStart = etinput_talkaugur.getSelectionStart();// 获取光标的位置
if (selectionStart > 0) {
String body = etinput_talkaugur.getText().toString();
String tempStr = body.substring(0, selectionStart);
int i = tempStr.lastIndexOf("[");// 获取最后一个表情的位置
if (i != -1) {
CharSequence cs = tempStr.substring(i, selectionStart);
if (SmileUtils.containsKey(cs.toString()))
etinput_talkaugur.getEditableText().delete(i, selectionStart);
else
etinput_talkaugur.getEditableText().delete(selectionStart - 1,
selectionStart);
} else {
etinput_talkaugur.getEditableText().delete(selectionStart - 1, selectionStart);
}
}
}
}
}
} catch (Exception e) {
}
}
});
return view;
}
public List getExpressionRes(int getSum) {
List reslist = new ArrayList();
for (int x = 1; x <= getSum; x++) {
String filename = "ee_" + x;
reslist.add(filename);
}
return reslist;
}
//--------发送消息的方法
protected void onGroupViewCreation() {
group = EMGroupManager.getInstance().getGroup(toChatUsername);
if (group != null) {
((TextView) findViewById(R.id.toolbar_title)).setText(group.getGroupName());
} else {
((TextView) findViewById(R.id.toolbar_title)).setText(toChatUsername);
}
}
protected void onChatRoomViewCreation() {
final ProgressDialog pd = ProgressDialog.show(this, "", "Joining......");
EMChatManager.getInstance().joinChatRoom(toChatUsername, new EMValueCallBack() {
@Override
public void onSuccess(EMChatRoom value) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
@Override
public void run() {
pd.dismiss();
room = EMChatManager.getInstance().getChatRoom(toChatUsername);
if (room != null) {
((TextView) findViewById(R.id.name)).setText(room.getName());
} else {
((TextView) findViewById(R.id.name)).setText(toChatUsername);
}
EMLog.d(TAG, "join room success : " + room.getName());
onConversationInit();
onListViewCreation();
}
});
}
@Override
public void onError(final int error, String errorMsg) {
// TODO Auto-generated method stub
EMLog.d(TAG, "join room failure : " + error);
runOnUiThread(new Runnable() {
@Override
public void run() {
pd.dismiss();
}
});
finish();
}
});
}
/**
* onActivityResult
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CODE_EXIT_GROUP) {
setResult(RESULT_OK);
finish();
return;
}
if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
switch (resultCode) {
case RESULT_CODE_COPY: // 复制消息
// EMMessage copyMsg = ((EMMessage) adapter.getItem(data.getIntExtra(“position”, -1)));
// // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this,
// // ((TextMessageBody) copyMsg.getBody()).getMessage()));
// clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage());
break;
case RESULT_CODE_DELETE: // 删除消息
// EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra(“position”, -1));
// conversation.removeMessage(deleteMsg.getMsgId());
// adapter.refreshSeekTo(data.getIntExtra(“position”, adapter.getCount()) - 1);
break;
case RESULT_CODE_FORWARD: // 转发消息
// EMMessage forwardMsg = (EMMessage) adapter.getItem(data.getIntExtra(“position”, 0));
// Intent intent = new Intent(this, ForwardMessageActivity.class);
// intent.putExtra(“forward_msg_id”, forwardMsg.getMsgId());
// startActivity(intent);
break;
default:
break;
}
}
if (resultCode == RESULT_OK) { // 清空消息
if (requestCode == REQUEST_CODE_EMPTY_HISTORY) {
// 清空会话
EMChatManager.getInstance().clearConversation(toChatUsername);
adapter.refresh();
} else if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片
if (cameraFile != null && cameraFile.exists())
sendPicture(cameraFile.getAbsolutePath());
} else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // 发送本地选择的视频
int duration = data.getIntExtra("dur", 0);
String videoPath = data.getStringExtra("path");
File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
Bitmap bitmap = null;
FileOutputStream fos = null;
try {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
if (bitmap == null) {
EMLog.d("chatactivity", "problem load video thumbnail bitmap,use default icon");
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.app_panel_video_icon);
}
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
fos = null;
}
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
}
sendVideo(videoPath, file.getAbsolutePath(), duration / 1000);
} else if (requestCode == REQUEST_CODE_LOCAL) { // 发送本地图片
if (data != null) {
Uri selectedImage = data.getData();
if (selectedImage != null) {
sendPicByUri(selectedImage);
}
}
} else if (requestCode == REQUEST_CODE_SELECT_FILE) { // 发送选择的文件
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
sendFile(uri);
}
}
} else if (requestCode == REQUEST_CODE_MAP) { // 地图
// 重发消息
} else if (requestCode == REQUEST_CODE_TEXT || requestCode == REQUEST_CODE_VOICE
|| requestCode == REQUEST_CODE_PICTURE || requestCode == REQUEST_CODE_LOCATION
|| requestCode == REQUEST_CODE_VIDEO || requestCode == REQUEST_CODE_FILE) {
resendMessage();
} else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) {
// 粘贴
if (!TextUtils.isEmpty(clipboard.getText())) {
String pasteText = clipboard.getText().toString();
if (pasteText.startsWith(COPY_IMAGE)) {
// 把图片前缀去掉,还原成正常的path
sendPicture(pasteText.replace(COPY_IMAGE, ""));
}
}
} else if (requestCode == REQUEST_CODE_ADD_TO_BLACKLIST) { // 移入黑名单
// EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra(“position”, -1));
// addUserToBlacklist(deleteMsg.getFrom());
} else if (conversation.getMsgCount() > 0) {
adapter.refresh();
setResult(RESULT_OK);
} else if (requestCode == REQUEST_CODE_GROUP_DETAIL) {
adapter.refresh();
}
}
}
/**
* 显示或隐藏图标按钮页
*
* @param view
*/
public void toggleMore(View view) {
if (more.getVisibility() == View.GONE) {
EMLog.d(TAG, "more gone");
hideKeyboard();
more.setVisibility(View.VISIBLE);
btnContainer.setVisibility(View.VISIBLE);
emojiIconContainer.setVisibility(View.GONE);
} else {
if (emojiIconContainer.getVisibility() == View.VISIBLE) {
emojiIconContainer.setVisibility(View.GONE);
btnContainer.setVisibility(View.VISIBLE);
iv_emoticons_normal.setVisibility(View.VISIBLE);
iv_emoticons_checked.setVisibility(View.INVISIBLE);
} else {
more.setVisibility(View.GONE);
}
}
}
/**
* 消息图标点击事件
*
* @param view
*/
@Override
public void onClick(View view) {
String st1 = getResources().getString(R.string.not_connect_to_server);
int id = view.getId();
if (id == R.id.btn_send) {// 点击发送按钮(发文字和表情)
// String s = etinput_talkaugur.getText().toString();
// sendText(s);
} else if (id == R.id.btn_take_picture) {
selectPicFromCamera();// 点击照相图标
} else if (id == R.id.btn_picture) {
selectPicFromLocal(); // 点击图片图标
} else if (id == R.id.btn_location) { // 位置
startActivityForResult(new Intent(this, BaiduMapActivity.class), REQUEST_CODE_MAP);
} else if (id == R.id.iv_emoticons_normal) { // 点击显示表情框
more.setVisibility(View.VISIBLE);
iv_emoticons_normal.setVisibility(View.INVISIBLE);
iv_emoticons_checked.setVisibility(View.VISIBLE);
btnContainer.setVisibility(View.GONE);
emojiIconContainer.setVisibility(View.VISIBLE);
hideKeyboard();
} else if (id == R.id.iv_emoticons_checked) { // 点击隐藏表情框
iv_emoticons_normal.setVisibility(View.VISIBLE);
iv_emoticons_checked.setVisibility(View.INVISIBLE);
btnContainer.setVisibility(View.VISIBLE);
emojiIconContainer.setVisibility(View.GONE);
more.setVisibility(View.GONE);
} else if (id == R.id.btn_video) {
// 点击摄像图标
// Intent intent = new Intent(ChatActivity.this, ImageGridActivity.class);
// startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
} else if (id == R.id.btn_file) { // 点击文件图标
selectFileFromLocal();
} else if (id == R.id.btn_voice_call) { // 点击语音电话图标
if (!EMChatManager.getInstance().isConnected())
Toast.makeText(this, st1, Toast.LENGTH_SHORT).show();
else {
// startActivity(new Intent(ChatActivity.this, VoiceCallActivity.class).putExtra(“username”,
// toChatUsername).putExtra(“isComingCall”, false));
// voiceCallBtn.setEnabled(false);
// toggleMore(null);
}
} else if (id == R.id.btn_video_call) { // 视频通话
if (!EMChatManager.getInstance().isConnected())
Toast.makeText(this, st1, Toast.LENGTH_SHORT).show();
else {
// startActivity(new Intent(this, VideoCallActivity.class).putExtra(“username”, toChatUsername).putExtra(
// “isComingCall”, false));
// videoCallBtn.setEnabled(false);
// toggleMore(null);
}
} else if (id == R.id.chatmain_container_focusnum) {
chatmain_container_focusnum_sel.setVisibility(View.VISIBLE);
chatmain_container_focusnum.setVisibility(View.GONE);
tv_chatmain_focusnum_sel.setText(“100”);
} else if (id == R.id.chatmain_container_focusnum_sel) {
chatmain_container_focusnum_sel.setVisibility(View.GONE);
chatmain_container_focusnum.setVisibility(View.VISIBLE);
tv_chatmain_focusnum.setText(“99”);
} else if (id == R.id.chat_tabs) {
fl_container_chatmain_history.setVisibility(View.GONE);
} else if (id == R.id.chat_vp_view) {
fl_container_chatmain_history.setVisibility(View.GONE);
}
}
/**
* 事件监听
*
* 根据不同的位置刷新UI
* see {@link EMNotifierEvent}
*/
@Override
public void onEvent(EMNotifierEvent event) {
switch (event.getEvent()) {
case EventNewMessage: {
//获取到message
EMMessage message = (EMMessage) event.getData();
String username = null;
//群组消息
if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
username = message.getTo();
} else {
//单聊消息
username = message.getFrom();
}
//如果是当前会话的消息,刷新聊天页面
if (username.equals(getToChatUsername())) {
refreshUIWithNewMessage();
//声音和震动提示有新消息
HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(message);
chatLookerFragment.onRefresh();
} else {
//如果消息不是和当前聊天ID的消息
HXSDKHelper.getInstance().getNotifier().onNewMsg(message);
chatLookerFragment.onRefresh();
}
break;
}
case EventDeliveryAck: {
//获取到message
EMMessage message = (EMMessage) event.getData();
refreshUI();
break;
}
case EventReadAck: {
//获取到message
EMMessage message = (EMMessage) event.getData();
refreshUI();
break;
}
case EventOfflineMessage: {
//a list of offline messages
//List offlineMessages = (List) event.getData();
refreshUI();
break;
}
default:
break;
}
}
public String getToChatUsername() {
return toChatUsername;
}
public ListView getListView() {
return listView;
}
private void refreshUIWithNewMessage() {
if (adapter == null) {
return;
}
runOnUiThread(new Runnable() {
public void run() {
adapter.refreshSelectLast();
}
});
}
private void refreshUI() {
if (adapter == null) {
return;
}
runOnUiThread(new Runnable() {
public void run() {
adapter.refresh();
}
});
}
/**
* 照相获取图片
*/
public void selectPicFromCamera() {
if (!CommonUtils.isExitsSdcard()) {
String st = getResources().getString(R.string.sd_card_does_not_exist);
Toast.makeText(getApplicationContext(), st, Toast.LENGTH_SHORT).show();
return;
}
cameraFile = new File(PathUtil.getInstance().getImagePath(), MyApplication.getInstance().getUserName()
+ System.currentTimeMillis() + ".jpg");
cameraFile.getParentFile().mkdirs();
startActivityForResult(
new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
REQUEST_CODE_CAMERA);
}
/**
* 选择文件
*/
private void selectFileFromLocal() {
Intent intent = null;
if (Build.VERSION.SDK_INT < 19) {
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);
}
/**
* 从图库获取图片
*/
public void selectPicFromLocal() {
Intent intent;
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
} else {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
}
startActivityForResult(intent, REQUEST_CODE_LOCAL);
}
/**
* 发送文本消息
*
* @param content message content
*/
public void sendText(String content) {
if (content.length() > 0) {
EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
// 如果是群聊,设置chattype,默认是单聊
if (chatType == CHATTYPE_GROUP) {
message.setChatType(EMMessage.ChatType.GroupChat);
} else if (chatType == CHATTYPE_CHATROOM) {
message.setChatType(EMMessage.ChatType.ChatRoom);
}
if (isRobot) {
message.setAttribute("em_robot_message", true);
}
TextMessageBody txtBody = new TextMessageBody(content);
// 设置消息body
message.addBody(txtBody);
// 设置要发给谁,用户username或者群聊groupid
message.setReceipt(toChatUsername);
// 把messgage加到conversation中
conversation.addMessage(message);
// 通知adapter有消息变动,adapter会根据加入的这条message显示消息和调用sdk的发送方法
adapter.refreshSelectLast();
etinput_talkaugur.setText("");
setResult(RESULT_OK);
}
}
/**
* 发送语音
*
* @param filePath
* @param fileName
* @param length
* @param isResend
*/
private void sendVoice(String filePath, String fileName, String length, boolean isResend) {
if (!(new File(filePath).exists())) {
return;
}
try {
final EMMessage message = EMMessage.createSendMessage(EMMessage.Type.VOICE);
// 如果是群聊,设置chattype,默认是单聊
if (chatType == CHATTYPE_GROUP) {
message.setChatType(EMMessage.ChatType.GroupChat);
} else if (chatType == CHATTYPE_CHATROOM) {
message.setChatType(EMMessage.ChatType.ChatRoom);
}
message.setReceipt(toChatUsername);
int len = Integer.parseInt(length);
VoiceMessageBody body = new VoiceMessageBody(new File(filePath), len);
message.addBody(body);
if (isRobot) {
message.setAttribute("em_robot_message", true);
}
conversation.addMessage(message);
adapter.refreshSelectLast();
setResult(RESULT_OK);
// send file
// sendVoiceSub(filePath, fileName, message);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送图片
*
* @param filePath
*/
private void sendPicture(final String filePath) {
String to = toChatUsername;
// create and add image message in view
final EMMessage message = EMMessage.createSendMessage(EMMessage.Type.IMAGE);
// 如果是群聊,设置chattype,默认是单聊
if (chatType == CHATTYPE_GROUP) {
message.setChatType(EMMessage.ChatType.GroupChat);
} else if (chatType == CHATTYPE_CHATROOM) {
message.setChatType(EMMessage.ChatType.ChatRoom);
}
message.setReceipt(to);
ImageMessageBody body = new ImageMessageBody(new File(filePath));
// 默认超过100k的图片会压缩后发给对方,可以设置成发送原图
// body.setSendOriginalImage(true);
message.addBody(body);
if (isRobot) {
message.setAttribute("em_robot_message", true);
}
conversation.addMessage(message);
listView.setAdapter(adapter);
adapter.refreshSelectLast();
setResult(RESULT_OK);
// more(more);
}
/**
* 发送视频消息
*/
private void sendVideo(final String filePath, final String thumbPath, final int length) {
final File videoFile = new File(filePath);
if (!videoFile.exists()) {
return;
}
try {
EMMessage message = EMMessage.createSendMessage(EMMessage.Type.VIDEO);
// 如果是群聊,设置chattype,默认是单聊
if (chatType == CHATTYPE_GROUP) {
message.setChatType(EMMessage.ChatType.GroupChat);
} else if (chatType == CHATTYPE_CHATROOM) {
message.setChatType(EMMessage.ChatType.ChatRoom);
}
String to = toChatUsername;
message.setReceipt(to);
VideoMessageBody body = new VideoMessageBody(videoFile, thumbPath, length, videoFile.length());
message.addBody(body);
if (isRobot) {
message.setAttribute("em_robot_message", true);
}
conversation.addMessage(message);
listView.setAdapter(adapter);
adapter.refreshSelectLast();
setResult(RESULT_OK);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据图库图片uri发送图片
*
* @param selectedImage
*/
private void sendPicByUri(Uri selectedImage) {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
String st8 = getResources().getString(R.string.cant_find_pictures);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
cursor = null;
if (picturePath == null || picturePath.equals("null")) {
Toast toast = Toast.makeText(this, st8, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
return;
}
sendPicture(picturePath);
} else {
File file = new File(selectedImage.getPath());
if (!file.exists()) {
Toast toast = Toast.makeText(this, st8, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
return;
}
sendPicture(file.getAbsolutePath());
}
}
/**
* 发送位置信息
*
* @param latitude
* @param longitude
* @param imagePath
* @param locationAddress
*/
private void sendLocationMsg(double latitude, double longitude, String imagePath, String locationAddress) {
EMMessage message = EMMessage.createSendMessage(EMMessage.Type.LOCATION);
// 如果是群聊,设置chattype,默认是单聊
if (chatType == CHATTYPE_GROUP) {
message.setChatType(EMMessage.ChatType.GroupChat);
} else if (chatType == CHATTYPE_CHATROOM) {
message.setChatType(EMMessage.ChatType.ChatRoom);
}
LocationMessageBody locBody = new LocationMessageBody(locationAddress, latitude, longitude);
message.addBody(locBody);
message.setReceipt(toChatUsername);
if (isRobot) {
message.setAttribute("em_robot_message", true);
}
conversation.addMessage(message);
listView.setAdapter(adapter);
adapter.refreshSelectLast();
setResult(RESULT_OK);
}
/**
* 发送文件
*
* @param uri
*/
private void sendFile(Uri uri) {
String filePath = null;
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {"_data"};
Cursor cursor = null;
try {
cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
filePath = cursor.getString(column_index);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
filePath = uri.getPath();
}
File file = new File(filePath);
if (file == null || !file.exists()) {
String st7 = getResources().getString(R.string.File_does_not_exist);
Toast.makeText(getApplicationContext(), st7, Toast.LENGTH_SHORT).show();
return;
}
if (file.length() > 10 * 1024 * 1024) {
String st6 = getResources().getString(R.string.The_file_is_not_greater_than_10_m);
Toast.makeText(getApplicationContext(), st6, Toast.LENGTH_SHORT).show();
return;
}
// 创建一个文件消息
EMMessage message = EMMessage.createSendMessage(EMMessage.Type.FILE);
// 如果是群聊,设置chattype,默认是单聊
if (chatType == CHATTYPE_GROUP) {
message.setChatType(EMMessage.ChatType.GroupChat);
} else if (chatType == CHATTYPE_CHATROOM) {
message.setChatType(EMMessage.ChatType.ChatRoom);
}
message.setReceipt(toChatUsername);
// add message body
NormalFileMessageBody body = new NormalFileMessageBody(new File(filePath));
message.addBody(body);
if (isRobot) {
message.setAttribute("em_robot_message", true);
}
conversation.addMessage(message);
listView.setAdapter(adapter);
adapter.refreshSelectLast();
setResult(RESULT_OK);
}
/**
* 重发消息
*/
private void resendMessage() {
EMMessage msg = null;
msg = conversation.getMessage(resendPos);
// msg.setBackSend(true);
msg.status = EMMessage.Status.CREATE;
adapter.refreshSeekTo(resendPos);
}
/**
* 隐藏软键盘
*/
private void hideKeyboard() {
if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
if (getCurrentFocus() != null)
manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/**
* 显示语音图标按钮
*
* @param view
*/
public void setModeVoice(View view) {
hideKeyboard();
edittext_layout.setVisibility(View.GONE);
more.setVisibility(View.GONE);
view.setVisibility(View.GONE);
buttonSetModeKeyboard.setVisibility(View.VISIBLE);
// buttonSend.setVisibility(View.GONE);
btnMore.setVisibility(View.VISIBLE);
buttonPressToSpeak.setVisibility(View.VISIBLE);
iv_emoticons_normal.setVisibility(View.VISIBLE);
iv_emoticons_checked.setVisibility(View.INVISIBLE);
btnContainer.setVisibility(View.VISIBLE);
emojiIconContainer.setVisibility(View.GONE);
}
/**
* 显示键盘图标
*
* @param view
*/
public void setModeKeyboard(View view) {
edittext_layout.setVisibility(View.VISIBLE);
more.setVisibility(View.GONE);
view.setVisibility(View.GONE);
//显示
buttonSetModeVoice.setVisibility(View.VISIBLE);
// etinput_talkaugur.setVisibility(View.VISIBLE);
etinput_talkaugur.requestFocus();
// buttonSend.setVisibility(View.VISIBLE);
buttonPressToSpeak.setVisibility(View.VISIBLE);
if (TextUtils.isEmpty(etinput_talkaugur.getText())) {
btnMore.setVisibility(View.VISIBLE);
// buttonSend.setVisibility(View.GONE);
} else {
btnMore.setVisibility(View.GONE);
// buttonSend.setVisibility(View.VISIBLE);
}
}
/**
* 点击清空聊天记录
*
* @param view
*/
public void emptyHistory(View view) {
String st5 = getResources().getString(R.string.Whether_to_empty_all_chats);
startActivityForResult(new Intent(this, AlertDialog.class).putExtra("titleIsCancel", true).putExtra("msg", st5)
.putExtra("cancel", true), REQUEST_CODE_EMPTY_HISTORY);
}
// chatdemo 监听 down
@Override
protected void onResume() {
super.onResume();
changeTab(mViewPager.getCurrentItem());
if (group != null)
// ((TextView) findViewById(R.id.name)).setText(group.getGroupName());
// voiceCallBtn.setEnabled(true);
// videoCallBtn.setEnabled(true);
if (adapter != null) {
adapter.refresh();
}
DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper.getInstance();
sdkHelper.pushActivity(this);
// register the event listener when enter the foreground
EMChatManager.getInstance().registerEventListener(
this,
new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage, EMNotifierEvent.Event.EventOfflineMessage,
EMNotifierEvent.Event.EventDeliveryAck, EMNotifierEvent.Event.EventReadAck});
}
}
这是 围观区的Fragment
package com.example.administrator.bazipaipan.chat.fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.easemob.EMCallBack;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.example.administrator.bazipaipan.BaseActivity;
import com.example.administrator.bazipaipan.MyApplication;
import com.example.administrator.bazipaipan.R;
import com.example.administrator.bazipaipan.chat.ChatContainerActivity;
import com.example.administrator.bazipaipan.chat.adapter.ChatGiftAdapter;
import com.example.administrator.bazipaipan.chat.adapter.ChatLookerAdapter;
import com.example.administrator.bazipaipan.chat.adapter.MyChatMsgAdapter;
import com.example.administrator.bazipaipan.chat.huanxin.DemoHXSDKHelper;
import com.example.administrator.bazipaipan.chat.model.Gift;
import com.example.administrator.bazipaipan.me.MeContainerActivity;
import com.example.administrator.bazipaipan.me.fragment.RechargeFragment;
import com.example.administrator.bazipaipan.widget.DividerItemDecoration;
import com.example.administrator.bazipaipan.widget.VerticalSwipeRefreshLayout;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import static android.support.v7.widget.LinearLayoutManager.HORIZONTAL;
/**
* Created by 王中阳 on 2016/1/2.
* 1围观区发送消息 群聊
*/
public class ChatLookerFragment extends Fragment implements ChatLookerAdapter.IClickListener, SwipeRefreshLayout.OnRefreshListener, TextView.OnEditorActionListener, View.OnClickListener, ChatGiftAdapter.IClickListener {
public static final String TAG = "ChatLookerFragment";
//1context
private ChatContainerActivity mycontext;
//2view对象
private ListView recyclerView;
//4适配器 围观区聊天
private MyChatMsgAdapter mAdapter;
//5网络加载更多
private VerticalSwipeRefreshLayout mSwipeLayout;
//控件
private EditText et_chatlooker_lookerinput; //围观推荐
private ImageView iv_chatlooker_givegift;
//赠送礼物
private RecyclerView rv_chatgift;
private Button btn_chatgift_recharge;
private TextView tv_giftpop_hot, tv_giftpop_all;
private LinearLayout chatlooker_container_givegift; //最外层容器
private ChatGiftAdapter chatGiftAdapter;
private List giftdatas;
//------2级礼物
private LinearLayout givegift_container_second, givegift_container_first;
private TextView tv_goldnum_givegift, tv_rechargebtn, tv_givegift_second_name, tv_givegift_second_goldnum;
private ImageView iv_givegift_second_head, iv_back_givegift;
private Button btn_givegift_second;
//聊天
private LinearLayout container_chatlooker_talkaugur, container_chatlooker_talkall;
private EMConversation conversation;
public static String roomID2 = null; // 2是围观群
NewMessageBroadcastReceiver msgReceiver;
//接口监听
static boolean isArrive = false;
public static ChatLookerFragment newInstance() {
ChatLookerFragment fragment = new ChatLookerFragment();
return fragment;
}
public ChatLookerFragment() {
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.mycontext = (ChatContainerActivity) context;
registerBroadcast(); //注册广播
}
private LinearLayout chatlooker_container_inputall;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//送礼物时隐藏键盘
container_chatlooker_talkaugur = (LinearLayout) mycontext.findViewById(R.id.container_chatlooker_talkaugur);
chatlooker_container_inputall = (LinearLayout) mycontext.findViewById(R.id.chatlooker_container_inputall);
roomID2 = MyApplication.getInstance().getRoomID2();
conversation = EMChatManager.getInstance().getConversation(roomID2);
updateUI();
}
private void registerBroadcast() {
msgReceiver = new NewMessageBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
intentFilter.setPriority(3);
mycontext.registerReceiver(msgReceiver, intentFilter);
EMChat.getInstance().setAppInited();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chatlooker, container, false);
et_chatlooker_lookerinput = (EditText) view.findViewById(R.id.et_chatlooker_lookerinput);
et_chatlooker_lookerinput.setOnEditorActionListener(this);
iv_chatlooker_givegift = (ImageView) view.findViewById(R.id.iv_chatlooker_givegift);
iv_chatlooker_givegift.setOnClickListener(this);
initTalk(view);
initGift(view);
isArrive = true;
ButterKnife.bind(this, view);
return view;
}
//聊天
private void initTalk(View view) {
container_chatlooker_talkall = (LinearLayout) view.findViewById(R.id.container_chatlooker_talkall);
container_chatlooker_talkall.setVisibility(View.VISIBLE);
}
@OnClick(R.id.iv_back_givegift_first)
public void hidegiveGift() {
chatlooker_container_givegift.setVisibility(View.GONE);
}
private void initGift(View view) {
//2级礼物
iv_givegift_second_head = (ImageView) view.findViewById(R.id.iv_givegift_second_head);
iv_back_givegift = (ImageView) view.findViewById(R.id.iv_back_givegift);
iv_back_givegift.setOnClickListener(this);
givegift_container_first = (LinearLayout) view.findViewById(R.id.givegift_container_first);
givegift_container_first.setOnClickListener(this);
givegift_container_second = (LinearLayout) view.findViewById(R.id.givegift_container_second);
givegift_container_second.setOnClickListener(this);
tv_goldnum_givegift = (TextView) view.findViewById(R.id.tv_goldnum_givegift);
tv_rechargebtn = (TextView) view.findViewById(R.id.tv_rechargebtn);
tv_rechargebtn.setOnClickListener(this);
tv_givegift_second_name = (TextView) view.findViewById(R.id.tv_givegift_second_name);
tv_givegift_second_goldnum = (TextView) view.findViewById(R.id.tv_givegift_second_goldnum);
btn_givegift_second = (Button) view.findViewById(R.id.btn_givegift_second);
btn_givegift_second.setOnClickListener(this);
//1级礼物
btn_chatgift_recharge = (Button) view.findViewById(R.id.btn_chatgift_recharge);
btn_chatgift_recharge.setOnClickListener(this);
tv_giftpop_hot = (TextView) view.findViewById(R.id.tv_giftpop_hot);
tv_giftpop_hot.setOnClickListener(this);
tv_giftpop_all = (TextView) view.findViewById(R.id.tv_giftpop_all);
tv_giftpop_all.setOnClickListener(this);
chatlooker_container_givegift = (LinearLayout) view.findViewById(R.id.chatlooker_container_givegift);
chatlooker_container_givegift.setOnClickListener(this);
rv_chatgift = (RecyclerView) view.findViewById(R.id.rv_chatgift);
//方向
rv_chatgift.setLayoutManager(new LinearLayoutManager(rv_chatgift.getContext(), HORIZONTAL, false));
//子布局装饰
rv_chatgift.addItemDecoration(new DividerItemDecoration(getContext(), HORIZONTAL));
//适配器未装填内容
chatGiftAdapter = new ChatGiftAdapter(mycontext, this);
rv_chatgift.setAdapter(chatGiftAdapter);
//滑动加载更多的layout
// mSwipeLayout = (VerticalSwipeRefreshLayout) view.findViewById(R.id.swipe_container);
// mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
// android.R.color.holo_blue_bright, android.R.color.holo_blue_bright,
// android.R.color.holo_blue_bright);
// //需要实现方法
// mSwipeLayout.setOnRefreshListener(this);
updateGiftDatas();
}
//更新赠送礼物的数据
private void updateGiftDatas() {
//查询多条数据
BmobQuery query = new BmobQuery<>();
giftdatas = new ArrayList<>();
//判断是否有缓存,该方法必须放在查询条件(如果有的话)都设置完之后再来调用才有效,就像这里一样。
boolean isCache = query.hasCachedResult(mycontext, Gift.class);
if (isCache) {
query.setCachePolicy(BmobQuery.CachePolicy.CACHE_ELSE_NETWORK); // 如果有缓存的话,则设置策略为CACHE_ELSE_NETWORK
} else {
query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE); // 如果没有缓存的话,则设置策略为NETWORK_ELSE_CACHE
}
query.findObjects(mycontext, new FindListener() {
@Override
public void onSuccess(List object) {
// TODO Auto-generated method stub
for (Gift bean : object) {
//数据源填充
giftdatas.add(bean);
}
chatGiftAdapter.setMdatas(giftdatas);
// mHandler.sendEmptyMessage(0);
// mSwipeLayout.setRefreshing(false);
}
@Override
public void onError(int code, String msg) {
// TODO Auto-generated method stub
// mHandler.sendEmptyMessage(0);
// mSwipeLayout.setRefreshing(false);
}
});
}
//做成girdview的样式
private void updateUI() {
recyclerView = (ListView) mycontext.findViewById(R.id.rv_chatlooker);
mAdapter = new MyChatMsgAdapter(conversation, mycontext, roomID2);
recyclerView.setAdapter(mAdapter);
}
@Override
public void onRefresh() {
// updateFromNet();
if (mAdapter != null) {
mAdapter.refresh();
}
}
//从网络中抓取数据,更新UI
private void updateFromNet() {
}
//点击item的跳转逻辑 赠送礼物跳转
@Override
public void onItemClicked(int position) {
// 逻辑 隐藏 及传参
secondShow();
}
//刷新数据相关
public void setSwipeToRefreshEnabled(boolean enabled) {
mSwipeLayout.setEnabled(enabled);
}
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
if (mSwipeLayout != null) {
if (mSwipeLayout.isRefreshing()) {
mSwipeLayout.setRefreshing(false);
}
}
break;
}
}
};
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
String sendtalkall;
//监听键盘发送功能
sendtalkall = et_chatlooker_lookerinput.getText().toString().trim();
if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
if (TextUtils.isEmpty(sendtalkall)) {
return false;
} else {
//获取到与聊天人的会话对象。参数username为聊天人的userid或者groupid,后文中的username皆是如此
EMConversation conversation = EMChatManager.getInstance().getConversation(roomID2);
//创建一条文本消息
EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
//如果是群聊,设置chattype,默认是单聊
message.setChatType(EMMessage.ChatType.GroupChat);
//设置消息body
TextMessageBody txtBody = new TextMessageBody(sendtalkall);
message.addBody(txtBody);
//设置接收人
message.setReceipt(roomID2);
//把消息加入到此会话对象中
conversation.addMessage(message);
//更新聊天列表消息
//原来的发送消息
mAdapter.refresh();
mAdapter.notifyDataSetChanged();
//发送消息
EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
@Override
public void onSuccess() {
}
@Override
public void onError(int i, String s) {
}
@Override
public void onProgress(int i, String s) {
}
});
//发送完毕清空回话框
et_chatlooker_lookerinput.setText("");
}
return true;
}
return false;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_chatlooker_givegift:
//显示礼物pop
chatlooker_container_givegift.setVisibility(View.VISIBLE);
break;
case R.id.tv_rechargebtn:
comRecharge();
break;
case R.id.btn_chatgift_recharge:
//充值按钮
comRecharge();
break;
case R.id.tv_giftpop_hot:
tv_giftpop_hot.setTextColor(getResources().getColor(R.color.tv_chatgold));
tv_giftpop_all.setTextColor(getResources().getColor(R.color.tv_black));
break;
case R.id.tv_giftpop_all:
tv_giftpop_hot.setTextColor(getResources().getColor(R.color.tv_black));
tv_giftpop_all.setTextColor(getResources().getColor(R.color.tv_chatgold));
break;
case R.id.iv_back_givegift:
firstShow();
break;
case R.id.btn_givegift_second:
// mycontext.toast(“礼物赠送成功”);
//金币不足, dialog
rechargeDialog();
break;
//发语音
case R.id.iv_chatlooker_voice:
break;
//键盘
case R.id.iv_chatlooker_key:
break;
}
}
//---------抽取方法----------
private void comRecharge() {
Intent intent = new Intent();
intent.setClass(getActivity(), MeContainerActivity.class);
intent.putExtra(BaseActivity.PAGETO, RechargeFragment.TAG);
mycontext.startActivity(intent);
}
private void firstShow() {
givegift_container_first.setVisibility(View.VISIBLE);
givegift_container_second.setVisibility(View.GONE);
//隐藏键盘
container_chatlooker_talkall.setVisibility(View.GONE);
// container_chatlooker_talkaugur.setVisibility(View.GONE);
chatlooker_container_inputall.setVisibility(View.GONE);
}
private void secondShow() {
givegift_container_second.setVisibility(View.VISIBLE);
givegift_container_first.setVisibility(View.GONE);
//隐藏键盘
container_chatlooker_talkall.setVisibility(View.GONE);
// container_chatlooker_talkaugur.setVisibility(View.GONE);
}
protected void rechargeDialog() {
AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(mycontext);
builder.setMessage("金币余额不足,赠送礼物失败");
// builder.setTitle(“提示”);
builder.setNegativeButton(“重新选择”, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
firstShow();
dialog.dismiss();
}
});
builder.setPositiveButton("获取金币", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
comRecharge();
dialog.dismiss();
}
});
builder.create().show();
}
/**
* 不能刷新数据
*/
@Override
public void onResume() {
super.onResume();
if (mAdapter != null) {
mAdapter.refresh();
}
DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper.getInstance();
sdkHelper.pushActivity(mycontext);
// register the event listener when enter the foreground
EMChatManager.getInstance().registerEventListener(
mycontext,
new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage, EMNotifierEvent.Event.EventOfflineMessage,
EMNotifierEvent.Event.EventDeliveryAck, EMNotifierEvent.Event.EventReadAck});
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onDetach() {
super.onDetach();
mycontext.unregisterReceiver(msgReceiver);
}
// 群聊方法抽取 up
private class NewMessageBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 注销广播
abortBroadcast();
// 消息id(每条消息都会生成唯一的一个id,目前是SDK生成)
String msgId = intent.getStringExtra("msgid");
//发送方
String username = intent.getStringExtra("from");
// 收到这个广播的时候,message已经在db和内存里了,可以通过id获取mesage对象
EMMessage message = EMChatManager.getInstance().getMessage(msgId);
EMConversation conversation = EMChatManager.getInstance().getConversation(username);
// 如果是群聊消息,获取到group id
if (message.getChatType() == EMMessage.ChatType.GroupChat) {
username = message.getTo();
}
if (!username.equals(username)) {
// 消息不是发给当前会话,return
return;
}
//更新消息
conversation.addMessage(message);
mAdapter.notifyDataSetChanged();
mAdapter.refresh();
}
}
// 群聊方法抽取 down
}
这是适配器
package com.example.administrator.bazipaipan.chat.adapter;
import android.app.Activity;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.example.administrator.bazipaipan.R;
import com.example.administrator.bazipaipan.chat.ChatContainerActivity;
/**
* Created by 王中阳 on 2015/12/16.
*/
public class MyChatMsgAdapter extends BaseAdapter {
private ChatContainerActivity mcontext;
private EMConversation conversation;
private TextView msg, username;
private Activity activity;
public MyChatMsgAdapter(EMConversation conversation, ChatContainerActivity mcontext, String username) {
// this.conversation = conversation;
this.conversation = EMChatManager.getInstance().getConversation(username);
this.mcontext = mcontext;
activity = mcontext;
}
EMMessage[] messages = null;
private static final int HANDLER_MESSAGE_REFRESH_LIST = 0;
private static final int HANDLER_MESSAGE_SELECT_LAST = 1;
private static final int HANDLER_MESSAGE_SEEK_TO = 2;
Handler handler = new Handler() {
private void refreshList() {
// UI线程不能直接使用conversation.getAllMessages()
// 否则在UI刷新过程中,如果收到新的消息,会导致并发问题
messages = (EMMessage[]) conversation.getAllMessages().toArray(new EMMessage[conversation.getAllMessages().size()]);
for (int i = 0; i < messages.length; i++) {
// getMessage will set message as read status
conversation.getMessage(i);
}
notifyDataSetChanged();
}
@Override
public void handleMessage(android.os.Message message) {
switch (message.what) {
case HANDLER_MESSAGE_REFRESH_LIST:
refreshList();
break;
// case HANDLER_MESSAGE_SELECT_LAST:
// if (activity instanceof ChatActivity) {
// ListView listView = ((ChatActivity) activity).getListView();
// if (messages.length > 0) {
// listView.setSelection(messages.length - 1);
// }
// }
// break;
// case HANDLER_MESSAGE_SEEK_TO:
// int position = message.arg1;
// if (activity instanceof ChatActivity) {
// ListView listView = ((ChatActivity) activity).getListView();
// listView.setSelection(position);
// }
// break;
default:
break;
}
}
};
/**
* 获取item数
*/
public int getCount() {
return messages == null ? 0 : messages.length;
}
/**
* 刷新页面, 选择最后一个
*/
public void refreshSelectLast() {
handler.sendMessage(handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST));
handler.sendMessage(handler.obtainMessage(HANDLER_MESSAGE_SELECT_LAST));
}
/**
* 刷新页面, 选择Position
*/
public void refreshSeekTo(int position) {
handler.sendMessage(handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST));
android.os.Message msg = handler.obtainMessage(HANDLER_MESSAGE_SEEK_TO);
msg.arg1 = position;
handler.sendMessage(msg);
}
public EMMessage getItem(int position) {
if (messages != null && position < messages.length) {
return messages[position];
}
return null;
}
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
EMMessage message = conversation.getAllMessages().get(position);
TextMessageBody body = (TextMessageBody) message.getBody();
if (message.direct == EMMessage.Direct.RECEIVE) {//接收方
if (message.getType() == EMMessage.Type.TXT) {
convertView = LayoutInflater.from(mcontext).inflate(R.layout.item_chatlooker, null);
username = (TextView) convertView.findViewById(R.id.tv_chatlooker_name);
username.setText(message.getFrom());
}
} else {
if (message.getType() == EMMessage.Type.TXT) { //发送方
convertView = LayoutInflater.from(mcontext).inflate(R.layout.item_chatlooker, null);
username = (TextView) convertView.findViewById(R.id.tv_chatlooker_name);
username.setText(message.getFrom());
}
}
msg = (TextView) convertView.findViewById(R.id.tv_chatlooker_comment);
msg.setText(body.getMessage());
return convertView;
}
/**
* 刷新页面
*/
public void refresh() {
if (handler.hasMessages(HANDLER_MESSAGE_REFRESH_LIST)) {
return;
}
android.os.Message msg = handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST);
handler.sendMessage(msg);
}
}
这是环信官方提供的适配器
/**
* Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.administrator.bazipaipan.chat.huanxin.adapter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Handler;
import android.text.Spannable;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;
import com.easemob.EMCallBack;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chat.EMMessage.Direct;
import com.easemob.chat.EMMessage.Type;
import com.easemob.chat.FileMessageBody;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.LocationMessageBody;
import com.easemob.chat.NormalFileMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.DateUtils;
import com.easemob.util.DensityUtil;
import com.easemob.util.EMLog;
import com.easemob.util.FileUtils;
import com.easemob.util.LatLng;
import com.easemob.util.TextFormater;
import com.example.administrator.bazipaipan.R;
import com.example.administrator.bazipaipan.chat.ChatContainerActivity;
import com.example.administrator.bazipaipan.chat.huanxin.Constant;
import com.example.administrator.bazipaipan.chat.huanxin.DemoHXSDKHelper;
import com.example.administrator.bazipaipan.chat.huanxin.activity.AlertDialog;
import com.example.administrator.bazipaipan.chat.huanxin.activity.BaiduMapActivity;
import com.example.administrator.bazipaipan.chat.huanxin.activity.ShowBigImage;
import com.example.administrator.bazipaipan.chat.huanxin.activity.ShowNormalFileActivity;
import com.example.administrator.bazipaipan.chat.huanxin.applib.controller.HXSDKHelper;
import com.example.administrator.bazipaipan.chat.huanxin.task.LoadImageTask;
import com.example.administrator.bazipaipan.chat.huanxin.utils.ImageCache;
import com.example.administrator.bazipaipan.chat.huanxin.utils.ImageUtils;
import com.example.administrator.bazipaipan.chat.huanxin.utils.SmileUtils;
import com.example.administrator.bazipaipan.chat.huanxin.utils.UserUtils;
import com.example.administrator.bazipaipan.utils.BmobUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import java.io.File;
import java.util.Date;
import java.util.Hashtable;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
public class MessageAdapter extends BaseAdapter {
private final static String TAG = "msg";
private static final int MESSAGE_TYPE_RECV_TXT = 0;
private static final int MESSAGE_TYPE_SENT_TXT = 1;
private static final int MESSAGE_TYPE_SENT_IMAGE = 2;
private static final int MESSAGE_TYPE_SENT_LOCATION = 3;
private static final int MESSAGE_TYPE_RECV_LOCATION = 4;
private static final int MESSAGE_TYPE_RECV_IMAGE = 5;
private static final int MESSAGE_TYPE_SENT_VOICE = 6;
private static final int MESSAGE_TYPE_RECV_VOICE = 7;
private static final int MESSAGE_TYPE_SENT_VIDEO = 8;
private static final int MESSAGE_TYPE_RECV_VIDEO = 9;
private static final int MESSAGE_TYPE_SENT_FILE = 10;
private static final int MESSAGE_TYPE_RECV_FILE = 11;
private static final int MESSAGE_TYPE_SENT_VOICE_CALL = 12;
private static final int MESSAGE_TYPE_RECV_VOICE_CALL = 13;
private static final int MESSAGE_TYPE_SENT_VIDEO_CALL = 14;
private static final int MESSAGE_TYPE_RECV_VIDEO_CALL = 15;
private static final int MESSAGE_TYPE_SENT_ROBOT_MENU = 16;
private static final int MESSAGE_TYPE_RECV_ROBOT_MENU = 17;
public static final String IMAGE_DIR = "chat/image/";
public static final String VOICE_DIR = "chat/audio/";
public static final String VIDEO_DIR = "chat/video";
private String username;
private LayoutInflater inflater;
private Activity activity;
private static final int HANDLER_MESSAGE_REFRESH_LIST = 0;
private static final int HANDLER_MESSAGE_SELECT_LAST = 1;
private static final int HANDLER_MESSAGE_SEEK_TO = 2;
// reference to conversation object in chatsdk
private EMConversation conversation;
EMMessage[] messages = null;
private Context context;
private Map timers = new Hashtable();
public MessageAdapter(Context context, String username, int chatType) {
this.username = username;
this.context = context;
inflater = LayoutInflater.from(context);
activity = (Activity) context;
this.conversation = EMChatManager.getInstance().getConversation(username);
}
Handler handler = new Handler() {
private void refreshList() {
// UI线程不能直接使用conversation.getAllMessages()
// 否则在UI刷新过程中,如果收到新的消息,会导致并发问题
messages = (EMMessage[]) conversation.getAllMessages().toArray(new EMMessage[conversation.getAllMessages().size()]);
for (int i = 0; i < messages.length; i++) {
// getMessage will set message as read status
conversation.getMessage(i);
}
notifyDataSetChanged();
}
@Override
public void handleMessage(android.os.Message message) {
switch (message.what) {
case HANDLER_MESSAGE_REFRESH_LIST:
refreshList();
break;
case HANDLER_MESSAGE_SELECT_LAST:
if (activity instanceof ChatContainerActivity) {
ListView listView = ((ChatContainerActivity) activity).getListView();
if (messages.length > 0) {
listView.setSelection(messages.length - 1);
}
}
break;
case HANDLER_MESSAGE_SEEK_TO:
int position = message.arg1;
if (activity instanceof ChatContainerActivity) {
ListView listView = ((ChatContainerActivity) activity).getListView();
listView.setSelection(position);
}
break;
default:
break;
}
}
};
/**
* 获取item数
*/
public int getCount() {
return messages == null ? 0 : messages.length;
}
/**
* 刷新页面
*/
public void refresh() {
if (handler.hasMessages(HANDLER_MESSAGE_REFRESH_LIST)) {
return;
}
android.os.Message msg = handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST);
handler.sendMessage(msg);
}
/**
* 刷新页面, 选择最后一个
*/
public void refreshSelectLast() {
handler.sendMessage(handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST));
handler.sendMessage(handler.obtainMessage(HANDLER_MESSAGE_SELECT_LAST));
}
/**
* 刷新页面, 选择Position
*/
public void refreshSeekTo(int position) {
handler.sendMessage(handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST));
android.os.Message msg = handler.obtainMessage(HANDLER_MESSAGE_SEEK_TO);
msg.arg1 = position;
handler.sendMessage(msg);
}
public EMMessage getItem(int position) {
if (messages != null && position < messages.length) {
return messages[position];
}
return null;
}
public long getItemId(int position) {
return position;
}
/**
* 获取item类型数
*/
public int getViewTypeCount() {
return 18;
}
/**
* 获取item类型
*/
public int getItemViewType(int position) {
EMMessage message = getItem(position);
if (message == null) {
return -1;
}
if (message.getType() == EMMessage.Type.TXT) {
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))
return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO_CALL : MESSAGE_TYPE_SENT_VIDEO_CALL;
else if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).isRobotMenuMessage(message))
return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_ROBOT_MENU : MESSAGE_TYPE_SENT_ROBOT_MENU;
else
return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_TXT : MESSAGE_TYPE_SENT_TXT;
}
if (message.getType() == EMMessage.Type.IMAGE) {
return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_IMAGE : MESSAGE_TYPE_SENT_IMAGE;
}
if (message.getType() == EMMessage.Type.LOCATION) {
return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_LOCATION : MESSAGE_TYPE_SENT_LOCATION;
}
if (message.getType() == EMMessage.Type.VOICE) {
return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE : MESSAGE_TYPE_SENT_VOICE;
}
if (message.getType() == EMMessage.Type.VIDEO) {
return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO : MESSAGE_TYPE_SENT_VIDEO;
}
if (message.getType() == EMMessage.Type.FILE) {
return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_FILE : MESSAGE_TYPE_SENT_FILE;
}
return -1;// invalid
}
private View createViewByMessage(EMMessage message, int position) {
switch (message.getType()) {
case LOCATION:
return message.direct == EMMessage.Direct.RECEIVE ? inflater.inflate(R.layout.row_received_location, null) : inflater.inflate(
R.layout.row_sent_location, null);
case IMAGE:
return message.direct == EMMessage.Direct.RECEIVE ? inflater.inflate(R.layout.row_received_picture, null) : inflater.inflate(
R.layout.row_sent_picture, null);
case VOICE:
return message.direct == EMMessage.Direct.RECEIVE ? inflater.inflate(R.layout.row_received_voice, null) : inflater.inflate(
R.layout.row_sent_voice, null);
case VIDEO:
return message.direct == EMMessage.Direct.RECEIVE ? inflater.inflate(R.layout.row_received_video, null) : inflater.inflate(
R.layout.row_sent_video, null);
case FILE:
return message.direct == EMMessage.Direct.RECEIVE ? inflater.inflate(R.layout.row_received_file, null) : inflater.inflate(
R.layout.row_sent_file, null);
default:
// 语音通话
if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false))
return message.direct == EMMessage.Direct.RECEIVE ? inflater.inflate(R.layout.row_received_voice_call, null) : inflater
.inflate(R.layout.row_sent_voice_call, null);
// 视频通话
else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false))
return message.direct == EMMessage.Direct.RECEIVE ? inflater.inflate(R.layout.row_received_video_call,
null) : inflater.inflate(R.layout.row_sent_video_call, null);
// 含有菜单的消息
else if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).isRobotMenuMessage(message))
return message.direct == EMMessage.Direct.RECEIVE ? inflater.inflate(R.layout.row_received_menu, null)
: inflater.inflate(R.layout.row_sent_message, null);
else
return message.direct == EMMessage.Direct.RECEIVE ? inflater.inflate(R.layout.row_received_message,
null) : inflater.inflate(R.layout.row_sent_message, null);
}
}
@SuppressLint("NewApi")
public View getView(final int position, View convertView, ViewGroup parent) {
final EMMessage message = getItem(position);
ChatType chatType = message.getChatType();
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = createViewByMessage(message, position);
if (message.getType() == EMMessage.Type.IMAGE) {
try {
holder.iv = ((ImageView) convertView.findViewById(R.id.iv_sendPicture));
holder.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_userhead);
holder.tv = (TextView) convertView.findViewById(R.id.percentage);
holder.pb = (ProgressBar) convertView.findViewById(R.id.progressBar);
holder.staus_iv = (ImageView) convertView.findViewById(R.id.msg_status);
holder.tv_usernick = (TextView) convertView.findViewById(R.id.tv_userid);
} catch (Exception e) {
}
} else if (message.getType() == EMMessage.Type.TXT) {
try {
holder.pb = (ProgressBar) convertView.findViewById(R.id.pb_sending);
holder.staus_iv = (ImageView) convertView.findViewById(R.id.msg_status);
holder.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_userhead);
// 这里是文字内容
holder.tv = (TextView) convertView.findViewById(R.id.tv_chatcontent);
holder.tv_usernick = (TextView) convertView.findViewById(R.id.tv_userid);
holder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
holder.tvList = (LinearLayout) convertView.findViewById(R.id.ll_layout);
} catch (Exception e) {
}
// 语音通话及视频通话
if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)
|| message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false)) {
holder.iv = (ImageView) convertView.findViewById(R.id.iv_call_icon);
holder.tv = (TextView) convertView.findViewById(R.id.tv_chatcontent);
}
} else if (message.getType() == EMMessage.Type.VOICE) {
try {
holder.iv = ((ImageView) convertView.findViewById(R.id.iv_voice));
holder.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_userhead);
holder.tv = (TextView) convertView.findViewById(R.id.tv_length);
holder.pb = (ProgressBar) convertView.findViewById(R.id.pb_sending);
holder.staus_iv = (ImageView) convertView.findViewById(R.id.msg_status);
holder.tv_usernick = (TextView) convertView.findViewById(R.id.tv_userid);
holder.iv_read_status = (ImageView) convertView.findViewById(R.id.iv_unread_voice);
} catch (Exception e) {
}
} else if (message.getType() == EMMessage.Type.LOCATION) {
try {
holder.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_userhead);
holder.tv = (TextView) convertView.findViewById(R.id.tv_location);
holder.pb = (ProgressBar) convertView.findViewById(R.id.pb_sending);
holder.staus_iv = (ImageView) convertView.findViewById(R.id.msg_status);
holder.tv_usernick = (TextView) convertView.findViewById(R.id.tv_userid);
} catch (Exception e) {
}
} else if (message.getType() == EMMessage.Type.VIDEO) {
try {
holder.iv = ((ImageView) convertView.findViewById(R.id.chatting_content_iv));
holder.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_userhead);
holder.tv = (TextView) convertView.findViewById(R.id.percentage);
holder.pb = (ProgressBar) convertView.findViewById(R.id.progressBar);
holder.staus_iv = (ImageView) convertView.findViewById(R.id.msg_status);
holder.size = (TextView) convertView.findViewById(R.id.chatting_size_iv);
holder.timeLength = (TextView) convertView.findViewById(R.id.chatting_length_iv);
holder.playBtn = (ImageView) convertView.findViewById(R.id.chatting_status_btn);
holder.container_status_btn = (LinearLayout) convertView.findViewById(R.id.container_status_btn);
holder.tv_usernick = (TextView) convertView.findViewById(R.id.tv_userid);
} catch (Exception e) {
}
} else if (message.getType() == EMMessage.Type.FILE) {
try {
holder.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_userhead);
holder.tv_file_name = (TextView) convertView.findViewById(R.id.tv_file_name);
holder.tv_file_size = (TextView) convertView.findViewById(R.id.tv_file_size);
holder.pb = (ProgressBar) convertView.findViewById(R.id.pb_sending);
holder.staus_iv = (ImageView) convertView.findViewById(R.id.msg_status);
holder.tv_file_download_state = (TextView) convertView.findViewById(R.id.tv_file_state);
holder.ll_container = (LinearLayout) convertView.findViewById(R.id.ll_file_container);
// 这里是进度值
holder.tv = (TextView) convertView.findViewById(R.id.percentage);
} catch (Exception e) {
}
try {
holder.tv_usernick = (TextView) convertView.findViewById(R.id.tv_userid);
} catch (Exception e) {
}
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// 群聊时,显示接收的消息的发送人的名称
if ((chatType == ChatType.GroupChat || chatType == ChatType.ChatRoom) && message.direct == EMMessage.Direct.RECEIVE) {
//demo里使用username代码nick
UserUtils.setUserNick(message.getFrom(), holder.tv_usernick);
}
if (message.direct == EMMessage.Direct.SEND) {
UserUtils.setCurrentUserNick(holder.tv_usernick);
}
// 如果是发送的消息并且不是群聊消息,显示已读textview
if (!(chatType == ChatType.GroupChat || chatType == ChatType.ChatRoom) && message.direct == EMMessage.Direct.SEND) {
holder.tv_ack = (TextView) convertView.findViewById(R.id.tv_ack);
holder.tv_delivered = (TextView) convertView.findViewById(R.id.tv_delivered);
if (holder.tv_ack != null) {
if (message.isAcked) {
if (holder.tv_delivered != null) {
holder.tv_delivered.setVisibility(View.INVISIBLE);
}
holder.tv_ack.setVisibility(View.VISIBLE);
} else {
holder.tv_ack.setVisibility(View.INVISIBLE);
// check and display msg delivered ack status
if (holder.tv_delivered != null) {
if (message.isDelivered) {
holder.tv_delivered.setVisibility(View.VISIBLE);
} else {
holder.tv_delivered.setVisibility(View.INVISIBLE);
}
}
}
}
} else {
// 如果是文本或者地图消息并且不是group messgae,chatroom message,显示的时候给对方发送已读回执
if ((message.getType() == Type.TXT || message.getType() == Type.LOCATION) && !message.isAcked && chatType != ChatType.GroupChat && chatType != ChatType.ChatRoom) {
// 不是语音通话记录
if (!message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) {
try {
EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
// 发送已读回执
message.isAcked = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//设置用户头像
setUserAvatar(message, holder.iv_avatar);
switch (message.getType()) {
// 根据消息type显示item
case IMAGE: // 图片
handleImageMessage(message, holder, position, convertView);
break;
case TXT: // 文本
if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)
|| message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false))
// 音视频通话
handleCallMessage(message, holder, position);
else if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).isRobotMenuMessage(message))
//含有列表的消息
handleRobotMenuMessage(message, holder, position);
else
handleTextMessage(message, holder, position);
break;
case LOCATION: // 位置
handleLocationMessage(message, holder, position, convertView);
break;
case VOICE: // 语音
handleVoiceMessage(message, holder, position, convertView);
break;
case VIDEO: // 视频
// handleVideoMessage(message, holder, position, convertView);
BmobUtils.log(“messageadapter 视频”);
break;
case FILE: // 一般文件
handleFileMessage(message, holder, position, convertView);
break;
default:
// not supported
}
if (message.direct == EMMessage.Direct.SEND) {
View statusView = convertView.findViewById(R.id.msg_status);
// 重发按钮点击事件
statusView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 显示重发消息的自定义alertdialog
Intent intent = new Intent(activity, AlertDialog.class);
intent.putExtra("msg", activity.getString(R.string.confirm_resend));
intent.putExtra("title", activity.getString(R.string.resend));
intent.putExtra("cancel", true);
intent.putExtra("position", position);
if (message.getType() == EMMessage.Type.TXT)
activity.startActivityForResult(intent, ChatContainerActivity.REQUEST_CODE_TEXT);
else if (message.getType() == EMMessage.Type.VOICE)
activity.startActivityForResult(intent, ChatContainerActivity.REQUEST_CODE_VOICE);
else if (message.getType() == EMMessage.Type.IMAGE)
activity.startActivityForResult(intent, ChatContainerActivity.REQUEST_CODE_PICTURE);
else if (message.getType() == EMMessage.Type.LOCATION)
activity.startActivityForResult(intent, ChatContainerActivity.REQUEST_CODE_LOCATION);
else if (message.getType() == EMMessage.Type.FILE)
activity.startActivityForResult(intent, ChatContainerActivity.REQUEST_CODE_FILE);
else if (message.getType() == EMMessage.Type.VIDEO)
activity.startActivityForResult(intent, ChatContainerActivity.REQUEST_CODE_VIDEO);
}
});
} else {
final String st = context.getResources().getString(R.string.Into_the_blacklist);
if (!((ChatContainerActivity) activity).isRobot && chatType != ChatType.ChatRoom) {
// 长按头像,移入黑名单
holder.iv_avatar.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent(activity, AlertDialog.class);
intent.putExtra("msg", st);
intent.putExtra("cancel", true);
intent.putExtra("position", position);
activity.startActivityForResult(intent, ChatContainerActivity.REQUEST_CODE_ADD_TO_BLACKLIST);
return true;
}
});
}
}
TextView timestamp = (TextView) convertView.findViewById(R.id.timestamp);
if (position == 0) {
timestamp.setText(DateUtils.getTimestampString(new Date(message.getMsgTime())));
timestamp.setVisibility(View.VISIBLE);
} else {
// 两条消息时间离得如果稍长,显示时间
EMMessage prevMessage = getItem(position - 1);
if (prevMessage != null && DateUtils.isCloseEnough(message.getMsgTime(), prevMessage.getMsgTime())) {
timestamp.setVisibility(View.GONE);
} else {
timestamp.setText(DateUtils.getTimestampString(new Date(message.getMsgTime())));
timestamp.setVisibility(View.VISIBLE);
}
}
return convertView;
}
/**
* 显示用户头像
*
* @param message
* @param imageView
*/
private void setUserAvatar(final EMMessage message, ImageView imageView) {
if (message.direct == Direct.SEND) {
//显示自己头像
UserUtils.setCurrentUserAvatar(context, imageView);
} else {
UserUtils.setUserAvatar(context, message.getFrom(), imageView);
}
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//点击头像查看用户信息
// Intent intent = new Intent();
// intent.setClass(context, UserProfileActivity.class);
// intent.putExtra(“username”, message.getFrom());
// context.startActivity(intent);
}
});
}
/**
* 文本消息
*
* @param message
* @param holder
* @param position
*/
private void handleTextMessage(EMMessage message, ViewHolder holder, final int position) {
TextMessageBody txtBody = (TextMessageBody) message.getBody();
Spannable span = SmileUtils.getSmiledText(context, txtBody.getMessage());
// 设置内容
holder.tv.setText(span, BufferType.SPANNABLE);
// 设置长按事件监听
holder.tv.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
activity.startActivityForResult(
(new Intent(activity, ContextMenu.class)).putExtra("position", position).putExtra("type",
EMMessage.Type.TXT.ordinal()), ChatContainerActivity.REQUEST_CODE_CONTEXT_MENU);
return true;
}
});
if (message.direct == EMMessage.Direct.SEND) {
switch (message.status) {
case SUCCESS: // 发送成功
holder.pb.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.GONE);
break;
case FAIL: // 发送失败
holder.pb.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.VISIBLE);
break;
case INPROGRESS: // 发送中
holder.pb.setVisibility(View.VISIBLE);
holder.staus_iv.setVisibility(View.GONE);
break;
default:
// 发送消息
sendMsgInBackground(message, holder);
}
}
}
private void setRobotMenuMessageLayout(LinearLayout parentView, JSONArray jsonArr) {
try {
parentView.removeAllViews();
for (int i = 0; i < jsonArr.length(); i++) {
final String itemStr = jsonArr.getString(i);
final TextView textView = new TextView(context);
textView.setText(itemStr);
textView.setTextSize(15);
try {
XmlPullParser xrp = context.getResources().getXml(R.drawable.menu_msg_text_color);
textView.setTextColor(ColorStateList.createFromXml(context.getResources(), xrp));
} catch (Exception e) {
e.printStackTrace();
}
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((ChatContainerActivity) context).sendText(itemStr);
}
});
LinearLayout.LayoutParams llLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
llLp.bottomMargin = DensityUtil.dip2px(context, 3);
llLp.topMargin = DensityUtil.dip2px(context, 3);
parentView.addView(textView, llLp);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void handleRobotMenuMessage(EMMessage message, ViewHolder holder, final int postion) {
try {
JSONObject jsonObj = message.getJSONObjectAttribute(Constant.MESSAGE_ATTR_ROBOT_MSGTYPE);
if (jsonObj.has("choice")) {
JSONObject jsonChoice = jsonObj.getJSONObject("choice");
String title = jsonChoice.getString("title");
holder.tvTitle.setText(title);
setRobotMenuMessageLayout(holder.tvList, jsonChoice.getJSONArray("list"));
}
} catch (Exception e) {
e.printStackTrace();
}
if (message.direct == EMMessage.Direct.SEND) {
switch (message.status) {
case SUCCESS: // 发送成功
holder.pb.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.GONE);
break;
case FAIL: // 发送失败
holder.pb.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.VISIBLE);
break;
case INPROGRESS: // 发送中
holder.pb.setVisibility(View.VISIBLE);
holder.staus_iv.setVisibility(View.GONE);
break;
default:
// 发送消息
sendMsgInBackground(message, holder);
}
}
}
/**
* 音视频通话记录
*
* @param message
* @param holder
* @param position
*/
private void handleCallMessage(EMMessage message, ViewHolder holder, final int position) {
TextMessageBody txtBody = (TextMessageBody) message.getBody();
holder.tv.setText(txtBody.getMessage());
}
/**
* 图片消息
*
* @param message
* @param holder
* @param position
* @param convertView
*/
private void handleImageMessage(final EMMessage message, final ViewHolder holder, final int position, View convertView) {
holder.pb.setTag(position);
holder.iv.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
activity.startActivityForResult(
(new Intent(activity, ContextMenu.class)).putExtra("position", position).putExtra("type",
EMMessage.Type.IMAGE.ordinal()), ChatContainerActivity.REQUEST_CODE_CONTEXT_MENU);
return true;
}
});
// 接收方向的消息
if (message.direct == EMMessage.Direct.RECEIVE) {
// "it is receive msg";
if (message.status == EMMessage.Status.INPROGRESS) {
// "!!!! back receive";
holder.iv.setImageResource(R.drawable.default_image);
showDownloadImageProgress(message, holder);
// downloadImage(message, holder);
} else {
// "!!!! not back receive, show image directly");
holder.pb.setVisibility(View.GONE);
holder.tv.setVisibility(View.GONE);
holder.iv.setImageResource(R.drawable.default_image);
ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
if (imgBody.getLocalUrl() != null) {
// String filePath = imgBody.getLocalUrl();
String remotePath = imgBody.getRemoteUrl();
String filePath = ImageUtils.getImagePath(remotePath);
String thumbRemoteUrl = imgBody.getThumbnailUrl();
if (TextUtils.isEmpty(thumbRemoteUrl) && !TextUtils.isEmpty(remotePath)) {
thumbRemoteUrl = remotePath;
}
String thumbnailPath = ImageUtils.getThumbnailImagePath(thumbRemoteUrl);
showImageView(thumbnailPath, holder.iv, filePath, imgBody.getRemoteUrl(), message);
}
}
return;
}
// 发送的消息
// process send message
// send pic, show the pic directly
ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
String filePath = imgBody.getLocalUrl();
if (filePath != null && new File(filePath).exists()) {
showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, null, message);
} else {
showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, IMAGE_DIR, message);
}
switch (message.status) {
case SUCCESS:
holder.pb.setVisibility(View.GONE);
holder.tv.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.GONE);
break;
case FAIL:
holder.pb.setVisibility(View.GONE);
holder.tv.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.VISIBLE);
break;
case INPROGRESS:
holder.staus_iv.setVisibility(View.GONE);
holder.pb.setVisibility(View.VISIBLE);
holder.tv.setVisibility(View.VISIBLE);
if (timers.containsKey(message.getMsgId()))
return;
// set a timer
final Timer timer = new Timer();
timers.put(message.getMsgId(), timer);
timer.schedule(new TimerTask() {
@Override
public void run() {
activity.runOnUiThread(new Runnable() {
public void run() {
holder.pb.setVisibility(View.VISIBLE);
holder.tv.setVisibility(View.VISIBLE);
holder.tv.setText(message.progress + "%");
if (message.status == EMMessage.Status.SUCCESS) {
holder.pb.setVisibility(View.GONE);
holder.tv.setVisibility(View.GONE);
// message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
timer.cancel();
} else if (message.status == EMMessage.Status.FAIL) {
holder.pb.setVisibility(View.GONE);
holder.tv.setVisibility(View.GONE);
// message.setSendingStatus(Message.SENDING_STATUS_FAIL);
// message.setProgress(0);
holder.staus_iv.setVisibility(View.VISIBLE);
Toast.makeText(activity,
activity.getString(R.string.send_fail) + activity.getString(R.string.connect_failuer_toast), Toast.LENGTH_SHORT)
.show();
timer.cancel();
}
}
});
}
}, 0, 500);
break;
default:
sendPictureMessage(message, holder);
}
}
/**
* 视频消息
*
* @param message
* @param holder
* @param position
* @param convertView
*/
// private void handleVideoMessage(final EMMessage message, final ViewHolder holder, final int position, View convertView) {
//
// VideoMessageBody videoBody = (VideoMessageBody) message.getBody();
// // final File image=new File(PathUtil.getInstance().getVideoPath(),
// // videoBody.getFileName());
// String localThumb = videoBody.getLocalThumb();
//
// holder.iv.setOnLongClickListener(new OnLongClickListener() {
//
// @Override
// public boolean onLongClick(View v) {
// activity.startActivityForResult(
// new Intent(activity, ContextMenu.class).putExtra(“position”, position).putExtra(“type”,
// EMMessage.Type.VIDEO.ordinal()), ChatContainerActivity.REQUEST_CODE_CONTEXT_MENU);
// return true;
// }
// });
//
// if (localThumb != null) {
//
// showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
// }
// if (videoBody.getLength() > 0) {
// String time = DateUtils.toTimeBySecond(videoBody.getLength());
// holder.timeLength.setText(time);
// }
// holder.playBtn.setImageResource(R.drawable.video_download_btn_nor);
//
// if (message.direct == EMMessage.Direct.RECEIVE) {
// if (videoBody.getVideoFileLength() > 0) {
// String size = TextFormater.getDataSize(videoBody.getVideoFileLength());
// holder.size.setText(size);
// }
// } else {
// if (videoBody.getLocalUrl() != null && new File(videoBody.getLocalUrl()).exists()) {
// String size = TextFormater.getDataSize(new File(videoBody.getLocalUrl()).length());
// holder.size.setText(size);
// }
// }
//
// if (message.direct == EMMessage.Direct.RECEIVE) {
//
// // System.err.println(“it is receive msg”);
// if (message.status == EMMessage.Status.INPROGRESS) {
// // System.err.println(“!!!! back receive”);
// holder.iv.setImageResource(R.drawable.default_image);
// showDownloadImageProgress(message, holder);
//
// } else {
// // System.err.println(“!!!! not back receive, show image directly”);
// holder.iv.setImageResource(R.drawable.default_image);
// if (localThumb != null) {
// showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
// }
//
// }
//
// return;
// }
// holder.pb.setTag(position);
//
// // until here ,deal with send video msg
// switch (message.status) {
// case SUCCESS:
// holder.pb.setVisibility(View.GONE);
// holder.staus_iv.setVisibility(View.GONE);
// holder.tv.setVisibility(View.GONE);
// break;
// case FAIL:
// holder.pb.setVisibility(View.GONE);
// holder.tv.setVisibility(View.GONE);
// holder.staus_iv.setVisibility(View.VISIBLE);
// break;
// case INPROGRESS:
// if (timers.containsKey(message.getMsgId()))
// return;
// // set a timer
// final Timer timer = new Timer();
// timers.put(message.getMsgId(), timer);
// timer.schedule(new TimerTask() {
//
// @Override
// public void run() {
// activity.runOnUiThread(new Runnable() {
//
// @Override
// public void run() {
// holder.pb.setVisibility(View.VISIBLE);
// holder.tv.setVisibility(View.VISIBLE);
// holder.tv.setText(message.progress + “%”);
// if (message.status == EMMessage.Status.SUCCESS) {
// holder.pb.setVisibility(View.GONE);
// holder.tv.setVisibility(View.GONE);
// // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
// timer.cancel();
// } else if (message.status == EMMessage.Status.FAIL) {
// holder.pb.setVisibility(View.GONE);
// holder.tv.setVisibility(View.GONE);
// // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
// // message.setProgress(0);
// holder.staus_iv.setVisibility(View.VISIBLE);
// Toast.makeText(activity,
// activity.getString(R.string.send_fail) + activity.getString(R.string.connect_failuer_toast), Toast.LENGTH_SHORT)
// .show();
// timer.cancel();
// }
//
// }
// });
//
// }
// }, 0, 500);
// break;
// default:
// // sendMsgInBackground(message, holder);
// sendPictureMessage(message, holder);
//
// }
//
// }
/**
* 语音消息
*
* @param message
* @param holder
* @param position
* @param convertView
*/
private void handleVoiceMessage(final EMMessage message, final ViewHolder holder, final int position, View convertView) {
VoiceMessageBody voiceBody = (VoiceMessageBody) message.getBody();
int len = voiceBody.getLength();
if (len > 0) {
holder.tv.setText(voiceBody.getLength() + "\"");
holder.tv.setVisibility(View.VISIBLE);
} else {
holder.tv.setVisibility(View.INVISIBLE);
}
holder.iv.setOnClickListener(new VoicePlayClickListener(message, holder.iv, holder.iv_read_status, this, activity, username));
holder.iv.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
activity.startActivityForResult(
(new Intent(activity, ContextMenu.class)).putExtra("position", position).putExtra("type",
EMMessage.Type.VOICE.ordinal()), ChatContainerActivity.REQUEST_CODE_CONTEXT_MENU);
return true;
}
});
if (((ChatContainerActivity) activity).playMsgId != null
&& ((ChatContainerActivity) activity).playMsgId.equals(message
.getMsgId()) && VoicePlayClickListener.isPlaying) {
AnimationDrawable voiceAnimation;
if (message.direct == EMMessage.Direct.RECEIVE) {
holder.iv.setImageResource(R.anim.voice_from_icon);
} else {
holder.iv.setImageResource(R.anim.voice_to_icon);
}
voiceAnimation = (AnimationDrawable) holder.iv.getDrawable();
voiceAnimation.start();
} else {
if (message.direct == EMMessage.Direct.RECEIVE) {
holder.iv.setImageResource(R.drawable.chatfrom_voice_playing);
} else {
holder.iv.setImageResource(R.drawable.chatto_voice_playing);
}
}
if (message.direct == EMMessage.Direct.RECEIVE) {
if (message.isListened()) {
// 隐藏语音未听标志
holder.iv_read_status.setVisibility(View.INVISIBLE);
} else {
holder.iv_read_status.setVisibility(View.VISIBLE);
}
EMLog.d(TAG, "it is receive msg");
if (message.status == EMMessage.Status.INPROGRESS) {
holder.pb.setVisibility(View.VISIBLE);
EMLog.d(TAG, "!!!! back receive");
((FileMessageBody) message.getBody()).setDownloadCallback(new EMCallBack() {
@Override
public void onSuccess() {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
holder.pb.setVisibility(View.INVISIBLE);
notifyDataSetChanged();
}
});
}
@Override
public void onProgress(int progress, String status) {
}
@Override
public void onError(int code, String message) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
holder.pb.setVisibility(View.INVISIBLE);
}
});
}
});
} else {
holder.pb.setVisibility(View.INVISIBLE);
}
return;
}
// until here, deal with send voice msg
switch (message.status) {
case SUCCESS:
holder.pb.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.GONE);
break;
case FAIL:
holder.pb.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.VISIBLE);
break;
case INPROGRESS:
holder.pb.setVisibility(View.VISIBLE);
holder.staus_iv.setVisibility(View.GONE);
break;
default:
sendMsgInBackground(message, holder);
}
}
/**
* 文件消息
*
* @param message
* @param holder
* @param position
* @param convertView
*/
private void handleFileMessage(final EMMessage message, final ViewHolder holder, int position, View convertView) {
final NormalFileMessageBody fileMessageBody = (NormalFileMessageBody) message.getBody();
final String filePath = fileMessageBody.getLocalUrl();
holder.tv_file_name.setText(fileMessageBody.getFileName());
holder.tv_file_size.setText(TextFormater.getDataSize(fileMessageBody.getFileSize()));
holder.ll_container.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
File file = new File(filePath);
if (file != null && file.exists()) {
// 文件存在,直接打开
FileUtils.openFile(file, (Activity) context);
} else {
// 下载
context.startActivity(new Intent(context, ShowNormalFileActivity.class).putExtra("msgbody", fileMessageBody));
}
if (message.direct == EMMessage.Direct.RECEIVE && !message.isAcked && message.getChatType() != ChatType.GroupChat && message.getChatType() != ChatType.ChatRoom) {
try {
EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
message.isAcked = true;
} catch (EaseMobException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
String st1 = context.getResources().getString(R.string.Have_downloaded);
String st2 = context.getResources().getString(R.string.Did_not_download);
if (message.direct == EMMessage.Direct.RECEIVE) { // 接收的消息
EMLog.d(TAG, "it is receive msg");
File file = new File(filePath);
if (file != null && file.exists()) {
holder.tv_file_download_state.setText(st1);
} else {
holder.tv_file_download_state.setText(st2);
}
return;
}
// until here, deal with send voice msg
switch (message.status) {
case SUCCESS:
holder.pb.setVisibility(View.INVISIBLE);
holder.tv.setVisibility(View.INVISIBLE);
holder.staus_iv.setVisibility(View.INVISIBLE);
break;
case FAIL:
holder.pb.setVisibility(View.INVISIBLE);
holder.tv.setVisibility(View.INVISIBLE);
holder.staus_iv.setVisibility(View.VISIBLE);
break;
case INPROGRESS:
if (timers.containsKey(message.getMsgId()))
return;
// set a timer
final Timer timer = new Timer();
timers.put(message.getMsgId(), timer);
timer.schedule(new TimerTask() {
@Override
public void run() {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
holder.pb.setVisibility(View.VISIBLE);
holder.tv.setVisibility(View.VISIBLE);
holder.tv.setText(message.progress + "%");
if (message.status == EMMessage.Status.SUCCESS) {
holder.pb.setVisibility(View.INVISIBLE);
holder.tv.setVisibility(View.INVISIBLE);
timer.cancel();
} else if (message.status == EMMessage.Status.FAIL) {
holder.pb.setVisibility(View.INVISIBLE);
holder.tv.setVisibility(View.INVISIBLE);
holder.staus_iv.setVisibility(View.VISIBLE);
Toast.makeText(activity,
activity.getString(R.string.send_fail) + activity.getString(R.string.connect_failuer_toast), Toast.LENGTH_SHORT)
.show();
timer.cancel();
}
}
});
}
}, 0, 500);
break;
default:
// 发送消息
sendMsgInBackground(message, holder);
}
}
/**
* 处理位置消息
*
* @param message
* @param holder
* @param position
* @param convertView
*/
private void handleLocationMessage(final EMMessage message, final ViewHolder holder, final int position, View convertView) {
TextView locationView = ((TextView) convertView.findViewById(R.id.tv_location));
LocationMessageBody locBody = (LocationMessageBody) message.getBody();
locationView.setText(locBody.getAddress());
LatLng loc = new LatLng(locBody.getLatitude(), locBody.getLongitude());
locationView.setOnClickListener(new MapClickListener(loc, locBody.getAddress()));
locationView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
activity.startActivityForResult(
(new Intent(activity, ContextMenu.class)).putExtra("position", position).putExtra("type",
EMMessage.Type.LOCATION.ordinal()), ChatContainerActivity.REQUEST_CODE_CONTEXT_MENU);
return false;
}
});
if (message.direct == EMMessage.Direct.RECEIVE) {
return;
}
// deal with send message
switch (message.status) {
case SUCCESS:
holder.pb.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.GONE);
break;
case FAIL:
holder.pb.setVisibility(View.GONE);
holder.staus_iv.setVisibility(View.VISIBLE);
break;
case INPROGRESS:
holder.pb.setVisibility(View.VISIBLE);
break;
default:
sendMsgInBackground(message, holder);
}
}
/**
* 发送消息
*
* @param message
* @param holder
*/
public void sendMsgInBackground(final EMMessage message, final ViewHolder holder) {
holder.staus_iv.setVisibility(View.GONE);
holder.pb.setVisibility(View.VISIBLE);
final long start = System.currentTimeMillis();
// 调用sdk发送异步发送方法
EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
@Override
public void onSuccess() {
updateSendedView(message, holder);
}
@Override
public void onError(int code, String error) {
updateSendedView(message, holder);
}
@Override
public void onProgress(int progress, String status) {
}
});
}
/*
* chat sdk will automatic download thumbnail image for the image message we
* need to register callback show the download progress
*/
private void showDownloadImageProgress(final EMMessage message, final ViewHolder holder) {
EMLog.d(TAG, "!!! show download image progress");
// final ImageMessageBody msgbody = (ImageMessageBody)
// message.getBody();
final FileMessageBody msgbody = (FileMessageBody) message.getBody();
if (holder.pb != null)
holder.pb.setVisibility(View.VISIBLE);
if (holder.tv != null)
holder.tv.setVisibility(View.VISIBLE);
msgbody.setDownloadCallback(new EMCallBack() {
@Override
public void onSuccess() {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
// message.setBackReceive(false);
if (message.getType() == EMMessage.Type.IMAGE) {
holder.pb.setVisibility(View.GONE);
holder.tv.setVisibility(View.GONE);
}
notifyDataSetChanged();
}
});
}
@Override
public void onError(int code, String message) {
}
@Override
public void onProgress(final int progress, String status) {
if (message.getType() == EMMessage.Type.IMAGE) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
holder.tv.setText(progress + "%");
}
});
}
}
});
}
/*
* send message with new sdk
*/
private void sendPictureMessage(final EMMessage message, final ViewHolder holder) {
try {
String to = message.getTo();
// before send, update ui
holder.staus_iv.setVisibility(View.GONE);
holder.pb.setVisibility(View.VISIBLE);
holder.tv.setVisibility(View.VISIBLE);
holder.tv.setText("0%");
final long start = System.currentTimeMillis();
// if (chatType == ChatContainerActivity.CHATTYPE_SINGLE) {
EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
@Override
public void onSuccess() {
Log.d(TAG, "send image message successfully");
activity.runOnUiThread(new Runnable() {
public void run() {
// send success
holder.pb.setVisibility(View.GONE);
holder.tv.setVisibility(View.GONE);
}
});
}
@Override
public void onError(int code, String error) {
activity.runOnUiThread(new Runnable() {
public void run() {
holder.pb.setVisibility(View.GONE);
holder.tv.setVisibility(View.GONE);
// message.setSendingStatus(Message.SENDING_STATUS_FAIL);
holder.staus_iv.setVisibility(View.VISIBLE);
Toast.makeText(activity,
activity.getString(R.string.send_fail) + activity.getString(R.string.connect_failuer_toast), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onProgress(final int progress, String status) {
activity.runOnUiThread(new Runnable() {
public void run() {
holder.tv.setText(progress + "%");
}
});
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 更新ui上消息发送状态
*
* @param message
* @param holder
*/
private void updateSendedView(final EMMessage message, final ViewHolder holder) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
// send success
if (message.getType() == EMMessage.Type.VIDEO) {
holder.tv.setVisibility(View.GONE);
}
EMLog.d(TAG, "message status : " + message.status);
if (message.status == EMMessage.Status.SUCCESS) {
// if (message.getType() == EMMessage.Type.FILE) {
// holder.pb.setVisibility(View.INVISIBLE);
// holder.staus_iv.setVisibility(View.INVISIBLE);
// } else {
// holder.pb.setVisibility(View.GONE);
// holder.staus_iv.setVisibility(View.GONE);
// }
} else if (message.status == EMMessage.Status.FAIL) {
// if (message.getType() == EMMessage.Type.FILE) {
// holder.pb.setVisibility(View.INVISIBLE);
// } else {
// holder.pb.setVisibility(View.GONE);
// }
// holder.staus_iv.setVisibility(View.VISIBLE);
//发消息失败的情况
if (message.getError() == EMError.MESSAGE_SEND_INVALID_CONTENT) {
Toast.makeText(activity, activity.getString(R.string.send_fail) + activity.getString(R.string.error_send_invalid_content), Toast.LENGTH_SHORT)
.show();
} else if (message.getError() == EMError.MESSAGE_SEND_NOT_IN_THE_GROUP) {
Toast.makeText(activity, activity.getString(R.string.send_fail) + activity.getString(R.string.error_send_not_in_the_group), Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(activity, activity.getString(R.string.send_fail) + activity.getString(R.string.connect_failuer_toast), Toast.LENGTH_SHORT)
.show();
}
}
notifyDataSetChanged();
}
});
}
/**
* load image into image view
*
* @param thumbernailPath
* @param iv
* @return the image exists or not
*/
private boolean showImageView(final String thumbernailPath, final ImageView iv, final String localFullSizePath, String remoteDir,
final EMMessage message) {
// String imagename =
// localFullSizePath.substring(localFullSizePath.lastIndexOf("/") + 1,
// localFullSizePath.length());
// final String remote = remoteDir != null ? remoteDir+imagename :
// imagename;
final String remote = remoteDir;
EMLog.d("###", "local = " + localFullSizePath + " remote: " + remote);
// first check if the thumbnail image already loaded into cache
Bitmap bitmap = ImageCache.getInstance().get(thumbernailPath);
if (bitmap != null) {
// thumbnail image is already loaded, reuse the drawable
iv.setImageBitmap(bitmap);
iv.setClickable(true);
iv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EMLog.d(TAG, "image view on click");
Intent intent = new Intent(activity, ShowBigImage.class);
File file = new File(localFullSizePath);
if (file.exists()) {
Uri uri = Uri.fromFile(file);
intent.putExtra("uri", uri);
EMLog.d(TAG, "here need to check why download everytime");
} else {
// The local full size pic does not exist yet.
// ShowBigImage needs to download it from the server
// first
// intent.putExtra("", message.get);
ImageMessageBody body = (ImageMessageBody) message.getBody();
intent.putExtra("secret", body.getSecret());
intent.putExtra("remotepath", remote);
}
if (message != null && message.direct == EMMessage.Direct.RECEIVE && !message.isAcked
&& message.getChatType() != ChatType.GroupChat && message.getChatType() != ChatType.ChatRoom) {
try {
EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
message.isAcked = true;
} catch (Exception e) {
e.printStackTrace();
}
}
activity.startActivity(intent);
}
});
return true;
} else {
new LoadImageTask().execute(thumbernailPath, localFullSizePath, remote, message.getChatType(), iv, activity, message);
return true;
}
}
/**
* 展示视频缩略图
*
* 本地缩略图路径
* 远程缩略图路径
*/
// private void showVideoThumbView(String localThumb, ImageView iv, String thumbnailUrl, final EMMessage message) {
// // first check if the thumbnail image already loaded into cache
// Bitmap bitmap = ImageCache.getInstance().get(localThumb);
// if (bitmap != null) {
// // thumbnail image is already loaded, reuse the drawable
// iv.setImageBitmap(bitmap);
// iv.setClickable(true);
// iv.setOnClickListener(new View.OnClickListener() {
//
// @Override
// public void onClick(View v) {
// VideoMessageBody videoBody = (VideoMessageBody) message.getBody();
// EMLog.d(TAG, “video view is on click”);
// Intent intent = new Intent(activity, ShowVideoActivity.class);
// intent.putExtra(“localpath”, videoBody.getLocalUrl());
// intent.putExtra(“secret”, videoBody.getSecret());
// intent.putExtra(“remotepath”, videoBody.getRemoteUrl());
// if (message != null && message.direct == EMMessage.Direct.RECEIVE && !message.isAcked
// && message.getChatType() != ChatType.GroupChat && message.getChatType() != ChatType.ChatRoom) {
// message.isAcked = true;
// try {
// EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// activity.startActivity(intent);
//
// }
// });
//
// } else {
// new LoadVideoImageTask().execute(localThumb, thumbnailUrl, iv, activity, message, this);
// }
//
// }
public static class ViewHolder {
ImageView iv;
TextView tv;
ProgressBar pb;
ImageView staus_iv;
ImageView iv_avatar;
TextView tv_usernick;
ImageView playBtn;
TextView timeLength;
TextView size;
LinearLayout container_status_btn;
LinearLayout ll_container;
ImageView iv_read_status;
// 显示已读回执状态
TextView tv_ack;
// 显示送达回执状态
TextView tv_delivered;
TextView tv_file_name;
TextView tv_file_size;
TextView tv_file_download_state;
TextView tvTitle;
LinearLayout tvList;
}
/*
* 点击地图消息listener
*/
class MapClickListener implements OnClickListener {
LatLng location;
String address;
public MapClickListener(LatLng loc, String address) {
location = loc;
this.address = address;
}
@Override
public void onClick(View v) {
Intent intent;
intent = new Intent(context, BaiduMapActivity.class);
intent.putExtra("latitude", location.latitude);
intent.putExtra("longitude", location.longitude);
intent.putExtra("address", address);
activity.startActivity(intent);
}
}
}