private void handleGroupChangeMsg(Message msg, ViewHolder holder, TextView msgTime) { UserInfo myInfo = JMessageClient.getMyInfo(); GroupInfo groupInfo = (GroupInfo) msg.getTargetInfo(); String content = ((EventNotificationContent) msg.getContent()).getEventText(); EventNotificationContent.EventNotificationType type = ((EventNotificationContent) msg.getContent()).getEventNotificationType(); switch (type) { case group_member_added: holder.groupChange.setText(content); holder.groupChange.setVisibility(View.VISIBLE); break; case group_member_exit: holder.groupChange.setVisibility(View.GONE); msgTime.setVisibility(View.GONE); break; case group_member_removed: List<String> userNames = ((EventNotificationContent) msg.getContent()).getUserNames(); // 被删除的人显示EventNotification if (userNames.contains(myInfo.getNickname()) || userNames.contains(myInfo.getUserName())) { holder.groupChange.setText(content); holder.groupChange.setVisibility(View.VISIBLE); // 群主亦显示 } else if (myInfo.getUserName().equals(groupInfo.getGroupOwner())) { holder.groupChange.setText(content); holder.groupChange.setVisibility(View.VISIBLE); } else { holder.groupChange.setVisibility(View.GONE); msgTime.setVisibility(View.GONE); } break; } }
// 正在发送文字或语音 private void sendingTextOrVoice(final ViewHolder holder, Animation sendingAnim, Message msg) { holder.sendingIv.setVisibility(View.VISIBLE); holder.sendingIv.startAnimation(sendingAnim); holder.resend.setVisibility(View.GONE); // 消息正在发送,重新注册一个监听消息发送完成的Callback if (!msg.isSendCompleteCallbackExists()) { msg.setOnSendCompleteCallback( new BasicCallback() { @Override public void gotResult(final int status, final String desc) { holder.sendingIv.setVisibility(View.GONE); holder.sendingIv.clearAnimation(); if (status == 803008) { CustomContent customContent = new CustomContent(); customContent.setBooleanValue("blackList", true); Message customMsg = mConv.createSendMessage(customContent); addMsgToList(customMsg); } else if (status != 0) { HandleResponseCode.onHandle(mContext, status, false); holder.resend.setVisibility(View.VISIBLE); } } }); } }
/** * 鍦ㄤ細璇濆垪琛ㄤ腑鎺ユ敹娑堟伅 * * @param event */ public void onEventMainThread(MessageEvent event) { Log.i(TAG, "onEventMainThread MessageEvent execute"); Message msg = event.getMessage(); String targetID = msg.getTargetID(); ConversationType convType = msg.getTargetType(); Conversation conv; if (convType == ConversationType.group) { conv = JMessageClient.getGroupConversation(Integer.parseInt(targetID)); } else { conv = JMessageClient.getSingleConversation(targetID); } if (conv != null && convType == ConversationType.single) { // 濡傛灉缂撳瓨浜嗗ご鍍忥紝鐩存帴鍒锋柊浼氳瘽鍒楄〃 if (NativeImageLoader.getInstance().getBitmapFromMemCache(targetID) != null) { Log.i("Test", "conversation "); mConvListController.refreshConvList(); // 娌℃湁澶村儚锛屼粠Conversation鎷� } else { File file = conv.getAvatarFile(); // 鎷垮埌鍚庣紦瀛樺苟鍒锋柊 if (file != null) { mConvListController.loadAvatarAndRefresh(targetID, file.getAbsolutePath()); // conversation涓病鏈夊ご鍍忥紝鐩存帴鍒锋柊锛孲DK浼氬湪鍚庡彴鑾峰緱澶村儚锛屾嬁鍒板悗浼氭墽琛宱nEvent(ConversationRefreshEvent // conversationRefreshEvent) } else mConvListController.refreshConvList(); } } else { mConvListController.refreshConvList(); } }
/** 检查图片是否处于创建状态,如果是,则加入发送队列 */ private void checkSendingImgMsg() { if (mMsgList.size() > 0) { for (Message msg : mMsgList) { if (msg.getStatus() == MessageStatus.created && msg.getContentType() == ContentType.image) { mMsgQueue.offer(msg); } } } }
private void sendingImage( final ViewHolder holder, final Animation sendingAnim, final Message msg) { holder.picture.setAlpha(0.75f); holder.sendingIv.setVisibility(View.VISIBLE); holder.sendingIv.startAnimation(sendingAnim); holder.progressTv.setVisibility(View.VISIBLE); holder.resend.setVisibility(View.GONE); // 如果图片正在发送,重新注册上传进度Callback if (!msg.isContentUploadProgressCallbackExists()) { msg.setOnContentUploadProgressCallback( new ProgressUpdateCallback() { @Override public void onProgressUpdate(double v) { String progressStr = (int) (v * 100) + "%"; Log.d(TAG, "msg.getId: " + msg.getId() + " progress: " + progressStr); holder.progressTv.setText(progressStr); } }); } if (!msg.isSendCompleteCallbackExists()) { msg.setOnSendCompleteCallback( new BasicCallback() { @Override public void gotResult(final int status, String desc) { Log.d(TAG, "Got result status: " + status); if (!mMsgQueue.isEmpty() && mMsgQueue.element().getId() == mSendMsgId) { mMsgQueue.poll(); if (!mMsgQueue.isEmpty()) { Message nextMsg = mMsgQueue.element(); JMessageClient.sendMessage(nextMsg); mSendMsgId = nextMsg.getId(); } } holder.picture.setAlpha(1.0f); holder.sendingIv.clearAnimation(); holder.sendingIv.setVisibility(View.GONE); holder.progressTv.setVisibility(View.GONE); if (status == 803008) { CustomContent customContent = new CustomContent(); customContent.setBooleanValue("blackList", true); Message customMsg = mConv.createSendMessage(customContent); addMsgToList(customMsg); } else if (status != 0) { HandleResponseCode.onHandle(mContext, status, false); holder.resend.setVisibility(View.VISIBLE); } Message message = mConv.getMessage(msg.getId()); mMsgList.set(mMsgList.indexOf(msg), message); Log.d(TAG, "msg.getId " + msg.getId() + " msg.getStatus " + msg.getStatus()); Log.d( TAG, "message.getId " + message.getId() + " message.getStatus " + message.getStatus()); } }); } }
public void getAllSingleConversation(JSONArray data, CallbackContext callbackContext) { Log.i(TAG, " getAllSingleConversation \n" + data); List<Conversation> list = JMessageClient.getConversationList(); Log.i(TAG, "JMessageGetAllSingleConversation" + list.size()); JSONArray jsonRusult = new JSONArray(); for (int i = 0; i < list.size(); ++i) { Conversation conv = list.get(i); if (conv.getType() == ConversationType.single) { UserInfo info = (UserInfo) conv.getTargetInfo(); Message msg = conv.getLatestMessage(); String contentText = ""; if (msg != null) { switch (msg.getContentType()) { case text: { contentText = ((TextContent) msg.getContent()).getText(); } break; default: break; } } JSONObject jsonItem = new JSONObject(); try { jsonItem.put("username", info.getUserName()); jsonItem.put("nickname", info.getNickname()); // jsonItem.put("avatar", info.getAvatar()); jsonItem.put("lastMessage", contentText); jsonItem.put("unreadCount", conv.getUnReadMsgCnt()); jsonRusult.put(jsonItem); } catch (JSONException e) { e.printStackTrace(); } } } callbackContext.success(jsonRusult); }
private void resendImage(final ViewHolder holder, Animation sendingAnim, Message msg) { ImageContent imgContent = (ImageContent) msg.getContent(); final String path = imgContent.getLocalThumbnailPath(); holder.sendingIv.setVisibility(View.VISIBLE); holder.sendingIv.startAnimation(sendingAnim); holder.picture.setAlpha(0.75f); holder.resend.setVisibility(View.GONE); holder.progressTv.setVisibility(View.VISIBLE); try { // 显示上传进度 msg.setOnContentUploadProgressCallback( new ProgressUpdateCallback() { @Override public void onProgressUpdate(final double progress) { mActivity.runOnUiThread( new Runnable() { @Override public void run() { String progressStr = (int) (progress * 100) + "%"; holder.progressTv.setText(progressStr); } }); } }); if (!msg.isSendCompleteCallbackExists()) { msg.setOnSendCompleteCallback( new BasicCallback() { @Override public void gotResult(final int status, String desc) { holder.sendingIv.clearAnimation(); holder.sendingIv.setVisibility(View.GONE); holder.progressTv.setVisibility(View.GONE); holder.picture.setAlpha(1.0f); if (status != 0) { HandleResponseCode.onHandle(mContext, status, false); holder.resend.setVisibility(View.VISIBLE); } } }); } JMessageClient.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); } }
private void handleCustomMsg(Message msg, ViewHolder holder) { CustomContent content = (CustomContent) msg.getContent(); Boolean isBlackListHint = content.getBooleanValue("blackList"); if (isBlackListHint != null && isBlackListHint) { holder.groupChange.setText(mContext.getString(R.string.server_803008)); } else { holder.groupChange.setVisibility(View.GONE); } }
public void onEventMainThread(MessageEvent event) { Message msg = event.getMessage(); TextContent content = (TextContent) msg.getContent(); SharedPreferences sp = getSharedPreferences("contracts", Activity.MODE_PRIVATE); String name = sp.getString("name", ""); if (!name.equals("") && name.equals(content.getText())) { String location = ""; if (ll != null) { location = String.valueOf(ll.latitude) + "," + String.valueOf(ll.longitude); } JMessageClient.sendMessage( JMessageClient.createSingleTextMessage( content.getText(), location.equals("") ? "failed" : location)); } else { } }
private void showAvatar(ImageView avatarView, Message msg) { File avatar = msg.getFromUser().getAvatarFile(); if (avatar != null) { ImageUtils.bindImageWithOptions( avatarView, avatar.getPath(), R.drawable.person_avatar_default_round, R.drawable.person_avatar_default_round); } }
public void onEvent(MessageEvent event) { final Message msg = event.getMessage(); Log.i(TAG, "onEvent:" + msg.toString()); // 可以在这里创建Notification if (msg.getTargetType() == ConversationType.single) { JSONObject obj = this.getJSonFormMessage(msg); Log.i(TAG, "@@@" + obj.toString()); PluginResult dataResult = new PluginResult(PluginResult.Status.OK, obj); dataResult.setKeepCallback(true); if (mJMessageReceiveCallback != null) { mJMessageReceiveCallback.sendPluginResult(dataResult); } } else { LOG.w(TAG, "message is not singleTyle"); } }
// 正在发送文字 private void sendingText(ViewHolder holder, Animation sendingAnim, Message msg) { holder.sendSending.setVisibility(View.VISIBLE); holder.sendSending.startAnimation(sendingAnim); holder.sendFail.setVisibility(View.GONE); // 消息正在发送,重新注册一个监听消息发送完成的Callback if (!msg.isSendCompleteCallbackExists()) { msg.setOnSendCompleteCallback( new BasicCallback() { @Override public void gotResult(final int status, final String desc) { mActivity.runOnUiThread( new Runnable() { @Override public void run() { if (status != 0) notifyDataSetChanged(); } }); } }); } }
private void resendText(final ViewHolder holder, Animation sendingAnim, Message msg) { holder.sendFail.setVisibility(View.GONE); holder.sendSending.setVisibility(View.VISIBLE); holder.sendSending.startAnimation(sendingAnim); if (!msg.isSendCompleteCallbackExists()) { msg.setOnSendCompleteCallback( new BasicCallback() { @Override public void gotResult(final int status, String desc) { if (status != 0) { holder.sendSending.clearAnimation(); holder.sendSending.setVisibility(View.GONE); holder.sendFail.setVisibility(View.VISIBLE); } notifyDataSetChanged(); } }); } JMessageClient.sendMessage(msg); }
private void resendTextOrVoice(final ViewHolder holder, Animation sendingAnim, Message msg) { holder.resend.setVisibility(View.GONE); holder.sendingIv.setVisibility(View.VISIBLE); holder.sendingIv.startAnimation(sendingAnim); if (!msg.isSendCompleteCallbackExists()) { msg.setOnSendCompleteCallback( new BasicCallback() { @Override public void gotResult(final int status, String desc) { holder.sendingIv.clearAnimation(); holder.sendingIv.setVisibility(View.GONE); if (status != 0) { HandleResponseCode.onHandle(mContext, status, false); holder.resend.setVisibility(View.VISIBLE); Log.i(TAG, "Resend message failed!"); } } }); } JMessageClient.sendMessage(msg); }
/** * 从发送队列中出列,并发送图片 * * @param msg 图片消息 */ private void sendNextImgMsg(Message msg) { JMessageClient.sendMessage(msg); msg.setOnSendCompleteCallback( new BasicCallback() { @Override public void gotResult(int i, String s) { // 出列 mMsgQueue.poll(); // 如果队列不为空,则继续发送下一张 if (!mMsgQueue.isEmpty()) { sendNextImgMsg(mMsgQueue.element()); } notifyDataSetChanged(); } }); }
@Override public int getItemViewType(int position) { Message msg = mMsgList.get(position); // 是文字类型或者自定义类型(用来显示群成员变化消息) if (msg.getContentType() == ContentType.text) { return msg.getDirect() == MessageDirect.send ? TYPE_SEND_TXT : TYPE_RECEIVE_TXT; } else if (msg.getContentType() == ContentType.image) { return msg.getDirect() == MessageDirect.send ? TYPE_SEND_IMAGE : TYPE_RECEIVER_IMAGE; } else if (msg.getContentType() == ContentType.voice) { return msg.getDirect() == MessageDirect.send ? TYPE_SEND_VOICE : TYPE_RECEIVER_VOICE; } else { return TYPE_CUSTOM_TXT; } }
private View createViewByType(Message msg, int position) { // 会话类型 switch (msg.getContentType()) { case image: return getItemViewType(position) == TYPE_SEND_IMAGE ? mInflater.inflate(R.layout.jmui_chat_item_send_image, null) : mInflater.inflate(R.layout.jmui_chat_item_receive_image, null); case voice: return getItemViewType(position) == TYPE_SEND_VOICE ? mInflater.inflate(R.layout.jmui_chat_item_send_voice, null) : mInflater.inflate(R.layout.jmui_chat_item_receive_voice, null); case text: return getItemViewType(position) == TYPE_SEND_TXT ? mInflater.inflate(R.layout.jmui_chat_item_send_text, null) : mInflater.inflate(R.layout.jmui_chat_item_receive_text, null); default: return mInflater.inflate(R.layout.jmui_chat_item_group_change, null); } }
private void handleTextMsg( final Message msg, final ViewHolder holder, OnLongClickListener longClickListener) { final String content = ((TextContent) msg.getContent()).getText(); holder.txtContent.setText(content); holder.txtContent.setOnLongClickListener(longClickListener); // 检查发送状态,发送方有重发机制 if (msg.getDirect() == MessageDirect.send) { final Animation sendingAnim = AnimationUtils.loadAnimation(mContext, R.anim.jmui_rotate); LinearInterpolator lin = new LinearInterpolator(); sendingAnim.setInterpolator(lin); switch (msg.getStatus()) { case send_success: holder.sendingIv.clearAnimation(); holder.sendingIv.setVisibility(View.GONE); holder.resend.setVisibility(View.GONE); break; case send_fail: holder.sendingIv.clearAnimation(); holder.sendingIv.setVisibility(View.GONE); holder.resend.setVisibility(View.VISIBLE); break; case send_going: sendingTextOrVoice(holder, sendingAnim, msg); break; default: } // 点击重发按钮,重发消息 holder.resend.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { showResendDialog(holder, sendingAnim, msg); } }); } else { if (mIsGroup) { holder.displayName.setVisibility(View.VISIBLE); if (TextUtils.isEmpty(msg.getFromUser().getNickname())) { holder.displayName.setText(msg.getFromUser().getUserName()); } else { holder.displayName.setText(msg.getFromUser().getNickname()); } } } }
@Override public View getView(int position, View convertView, ViewGroup parent) { Message msg = mMsgList.get(position); ViewHolder holder = new ViewHolder(); convertView = createViewByType(msg, position); if (msg.getDirect().equals(MessageDirect.send)) { holder.sendTime = (TextView) convertView.findViewById(R.id.send_time_txt); holder.sendAvatar = (CircleImageView) convertView.findViewById(R.id.send_avatar_iv); holder.sendFail = (ImageButton) convertView.findViewById(R.id.send_fail_resend_ib); holder.sendMsg = (TextView) convertView.findViewById(R.id.send_msg_content); holder.sendSending = (ImageView) convertView.findViewById(R.id.send_sending_iv); } else if (msg.getDirect().equals(MessageDirect.receive)) { holder.receiveTime = (TextView) convertView.findViewById(R.id.receive_time_txt); holder.receiveAvatar = (CircleImageView) convertView.findViewById(R.id.receive_avatar_iv); holder.receiveMsg = (TextView) convertView.findViewById(R.id.receive_msg_content); } if (msg.getDirect().equals(MessageDirect.receive)) { showTime(holder.receiveTime, msg, position); showAvatar(holder.receiveAvatar, msg); String content = ((TextContent) msg.getContent()).getText(); holder.receiveMsg.setText(content); } if (msg.getDirect().equals(MessageDirect.send)) { showTime(holder.sendTime, msg, position); String userID = PrefUtils.getString(context, "loginUser", null); User user = new DatabaseUtils(context).queryUser(userID); ImageUtils.bindImageWithOptions( holder.sendAvatar, user.user_avatar, R.drawable.person_avatar_default_round, R.drawable.person_avatar_default_round); String content = ((TextContent) msg.getContent()).getText(); holder.sendMsg.setText(content); handleTextMsg(msg, holder); } return convertView; }
/** 显示时间 */ private void showTime(TextView msgTime, Message msg, int position) { long nowDate = msg.getCreateTime(); if (mOffset == 18) { if (position == 0 || position % 18 == 0) { TimeFormat timeFormat = new TimeFormat(context, nowDate); msgTime.setText(timeFormat.getDetailTime()); msgTime.setVisibility(View.VISIBLE); } else { long lastDate = mMsgList.get(position - 1).getCreateTime(); // 如果两条消息之间的间隔超过十分钟则显示时间 if (nowDate - lastDate > 600000) { TimeFormat timeFormat = new TimeFormat(context, nowDate); msgTime.setText(timeFormat.getDetailTime()); msgTime.setVisibility(View.VISIBLE); } else { msgTime.setVisibility(View.GONE); } } } else { if (position == 0 || position == mOffset || (position - mOffset) % 18 == 0) { TimeFormat timeFormat = new TimeFormat(context, nowDate); msgTime.setText(timeFormat.getDetailTime()); msgTime.setVisibility(View.VISIBLE); } else { long lastDate = mMsgList.get(position - 1).getCreateTime(); // 如果两条消息之间的间隔超过十分钟则显示时间 if (nowDate - lastDate > 600000) { TimeFormat timeFormat = new TimeFormat(context, nowDate); msgTime.setText(timeFormat.getDetailTime()); msgTime.setVisibility(View.VISIBLE); } else { msgTime.setVisibility(View.GONE); } } } }
private JSONObject getJSonFormMessage(Message msg) { String contentText = ""; String msgType = ""; // 上传给js 层的类型,请和ios 保持一致 switch (msg.getContentType()) { case text: contentText = ((TextContent) msg.getContent()).getText(); msgType = "text"; break; default: break; } Log.i(TAG, "msg " + contentText); JSONObject jsonItem = new JSONObject(); try { MessageContent content = msg.getContent(); UserInfo targetUser = (UserInfo) msg.getTargetInfo(); UserInfo fromUser = (UserInfo) msg.getFromUser(); jsonItem.put("target_type", "single"); jsonItem.put("target_id", targetUser.getUserName()); jsonItem.put("target_name", targetUser.getNickname()); jsonItem.put("from_id", fromUser.getUserName()); // jsonItem.put("from_name", fromUser.getNickname()); jsonItem.put("from_name", msg.getFromName()); jsonItem.put("create_time", msg.getCreateTime()); jsonItem.put("msg_type", msgType); // jsonItem.put("text", contentText); JSONObject contentBody = new JSONObject(); contentBody.put("text", contentText); jsonItem.put("msg_body", contentBody); } catch (JSONException e) { e.printStackTrace(); } return jsonItem; }
private void handleTextMsg(final Message msg, final ViewHolder holder) { // 检查发送状态,发送方有重发机制 final Animation sendingAnim = AnimationUtils.loadAnimation(context, R.anim.rotate); LinearInterpolator lin = new LinearInterpolator(); sendingAnim.setInterpolator(lin); switch (msg.getStatus()) { case send_success: if (sendingAnim != null) { holder.sendSending.clearAnimation(); holder.sendSending.setVisibility(View.GONE); } holder.sendFail.setVisibility(View.GONE); break; case send_fail: if (sendingAnim != null) { holder.sendSending.clearAnimation(); holder.sendSending.setVisibility(View.GONE); } holder.sendFail.setVisibility(View.VISIBLE); break; case send_going: sendingText(holder, sendingAnim, msg); break; default: break; } // 点击重发按钮,重发消息 holder.sendFail.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("重发按钮被点击!"); showResendDialog(holder, sendingAnim, msg); } }); }
@Override public int getItemViewType(int position) { Message msg = mMsgList.get(position); return msg.getDirect().equals(MessageDirect.send) ? TYPE_SEND_TXT : TYPE_RECEIVE_TXT; }
/** * 接收消息类事件 * * @param event 消息事件 */ public void onEvent(MessageEvent event) { final Message msg = event.getMessage(); // 若为群聊相关事件,如添加、删除群成员 Log.i(TAG, event.getMessage().toString()); if (msg.getContentType() == ContentType.eventNotification) { GroupInfo groupInfo = (GroupInfo) msg.getTargetInfo(); long groupID = groupInfo.getGroupID(); UserInfo myInfo = JMessageClient.getMyInfo(); EventNotificationContent.EventNotificationType type = ((EventNotificationContent) msg.getContent()).getEventNotificationType(); if (groupID == mChatController.getGroupId()) { switch (type) { case group_member_added: // 添加群成员事件 List<String> userNames = ((EventNotificationContent) msg.getContent()).getUserNames(); // 群主把当前用户添加到群聊,则显示聊天详情按钮 refreshGroupNum(); if (userNames.contains(myInfo.getNickname()) || userNames.contains(myInfo.getUserName())) { runOnUiThread( new Runnable() { @Override public void run() { mChatView.showRightBtn(); } }); } break; case group_member_removed: // 删除群成员事件 userNames = ((EventNotificationContent) msg.getContent()).getUserNames(); // 群主删除了当前用户,则隐藏聊天详情按钮 if (userNames.contains(myInfo.getNickname()) || userNames.contains(myInfo.getUserName())) { runOnUiThread( new Runnable() { @Override public void run() { mChatView.dismissRightBtn(); GroupInfo groupInfo = (GroupInfo) mChatController.getConversation().getTargetInfo(); if (TextUtils.isEmpty(groupInfo.getGroupName())) { mChatView.setChatTitle(ChatActivity.this.getString(R.string.group)); } else { mChatView.setChatTitle(groupInfo.getGroupName()); } mChatView.dismissGroupNum(); } }); } else { refreshGroupNum(); } break; case group_member_exit: refreshGroupNum(); break; } } } // 刷新消息 runOnUiThread( new Runnable() { @Override public void run() { // 收到消息的类型为单聊 if (msg.getTargetType().equals(ConversationType.single)) { String targetID = ((UserInfo) msg.getTargetInfo()).getUserName(); // 判断消息是否在当前会话中 if (!mChatController.isGroup() && targetID.equals(mChatController.getTargetId())) { Message lastMsg = mChatController.getAdapter().getLastMsg(); if (lastMsg == null || msg.getId() != lastMsg.getId()) { mChatController.getAdapter().addMsgToList(msg); } else { mChatController.getAdapter().notifyDataSetChanged(); } } } else { long groupID = ((GroupInfo) msg.getTargetInfo()).getGroupID(); if (mChatController.isGroup() && groupID == mChatController.getGroupId()) { Message lastMsg = mChatController.getAdapter().getLastMsg(); if (lastMsg == null || msg.getId() != lastMsg.getId()) { mChatController.getAdapter().addMsgToList(msg); } else { mChatController.getAdapter().notifyDataSetChanged(); } } } } }); }
private void handleVoiceMsg( final Message msg, final ViewHolder holder, final int position, OnLongClickListener longClickListener) { final VoiceContent content = (VoiceContent) msg.getContent(); final MessageDirect msgDirect = msg.getDirect(); int length = content.getDuration(); String voiceLength = length + mContext.getString(R.string.symbol_second); holder.voiceLength.setText(voiceLength); // 控制语音长度显示,长度增幅随语音长度逐渐缩小 int width = (int) (-0.04 * length * length + 4.526 * length + 75.214); holder.txtContent.setWidth((int) (width * mDensity)); holder.txtContent.setOnLongClickListener(longClickListener); if (msgDirect == MessageDirect.send) { holder.voice.setImageResource(R.drawable.jmui_send_3); final Animation sendingAnim = AnimationUtils.loadAnimation(mContext, R.anim.jmui_rotate); LinearInterpolator lin = new LinearInterpolator(); sendingAnim.setInterpolator(lin); switch (msg.getStatus()) { case send_success: holder.sendingIv.clearAnimation(); holder.sendingIv.setVisibility(View.GONE); holder.resend.setVisibility(View.GONE); break; case send_fail: holder.sendingIv.clearAnimation(); holder.sendingIv.setVisibility(View.GONE); holder.resend.setVisibility(View.VISIBLE); break; case send_going: sendingTextOrVoice(holder, sendingAnim, msg); break; default: } holder.resend.setOnClickListener( new OnClickListener() { @Override public void onClick(View arg0) { if (msg.getContent() != null) { showResendDialog(holder, sendingAnim, msg); } else { Toast.makeText( mContext, mContext.getString(R.string.sdcard_not_exist_toast), Toast.LENGTH_SHORT) .show(); } } }); } else switch (msg.getStatus()) { case receive_success: if (mIsGroup) { holder.displayName.setVisibility(View.VISIBLE); if (TextUtils.isEmpty(msg.getFromUser().getNickname())) { holder.displayName.setText(msg.getFromUser().getUserName()); } else { holder.displayName.setText(msg.getFromUser().getNickname()); } } holder.voice.setImageResource(R.drawable.jmui_receive_3); // 收到语音,设置未读 if (msg.getContent().getBooleanExtra("isReaded") == null || !msg.getContent().getBooleanExtra("isReaded")) { mConv.updateMessageExtra(msg, "isReaded", false); holder.readStatus.setVisibility(View.VISIBLE); if (mIndexList.size() > 0) { if (!mIndexList.contains(position)) { addTolistAndSort(position); } } else { addTolistAndSort(position); } if (nextPlayPosition == position && autoPlay) { playVoice(position, holder, false); } } else if (msg.getContent().getBooleanExtra("isReaded").equals(true)) { holder.readStatus.setVisibility(View.GONE); } break; case receive_fail: holder.voice.setImageResource(R.drawable.jmui_receive_3); // 接收失败,从服务器上下载 content.downloadVoiceFile( msg, new DownloadCompletionCallback() { @Override public void onComplete(int status, String desc, File file) { if (status != 0) { Toast.makeText( mContext, mContext.getString(R.string.voice_fetch_failed_toast), Toast.LENGTH_SHORT) .show(); } else { Log.i("VoiceMessage", "reload success"); } } }); break; case receive_going: break; default: } holder.txtContent.setOnClickListener( new OnClickListener() { @Override public void onClick(View arg0) { if (!FileHelper.isSdCardExist() && msg.getDirect() == MessageDirect.send) { Toast.makeText( mContext, mContext.getString(R.string.sdcard_not_exist_toast), Toast.LENGTH_SHORT) .show(); return; } // 如果之前存在播放动画,无论这次点击触发的是暂停还是播放,停止上次播放的动画 if (mVoiceAnimation != null) { mVoiceAnimation.stop(); } // 播放中点击了正在播放的Item 则暂停播放 if (mp.isPlaying() && mPosition == position) { if (msgDirect == MessageDirect.send) { holder.voice.setImageResource(R.anim.jmui_voice_send); } else { holder.voice.setImageResource(R.anim.jmui_voice_receive); } mVoiceAnimation = (AnimationDrawable) holder.voice.getDrawable(); pauseVoice(); mVoiceAnimation.stop(); // 开始播放录音 } else if (msgDirect == MessageDirect.send) { holder.voice.setImageResource(R.anim.jmui_voice_send); mVoiceAnimation = (AnimationDrawable) holder.voice.getDrawable(); // 继续播放之前暂停的录音 if (mSetData && mPosition == position) { mVoiceAnimation.start(); mp.start(); // 否则重新播放该录音或者其他录音 } else { playVoice(position, holder, true); } // 语音接收方特殊处理,自动连续播放未读语音 } else { try { // 继续播放之前暂停的录音 if (mSetData && mPosition == position) { if (mVoiceAnimation != null) { mVoiceAnimation.start(); } mp.start(); // 否则开始播放另一条录音 } else { // 选中的录音是否已经播放过,如果未播放,自动连续播放这条语音之后未播放的语音 if (msg.getContent().getBooleanExtra("isReaded") == null || !msg.getContent().getBooleanExtra("isReaded")) { autoPlay = true; playVoice(position, holder, false); // 否则直接播放选中的语音 } else { holder.voice.setImageResource(R.anim.jmui_voice_receive); mVoiceAnimation = (AnimationDrawable) holder.voice.getDrawable(); playVoice(position, holder, false); } } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } } } }); }
@Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { // 返回按钮 case R.id.return_btn: mConv.resetUnreadCount(); JMessageClient.exitConversaion(); mContext.finish(); break; // 聊天详细信息 case R.id.right_btn: if (mIsShowMoreMenu) { mChatView.dismissMoreMenu(); dismissSoftInput(); mIsShowMoreMenu = false; } mContext.StartChatDetailActivity(mIsGroup, mTargetID, mGroupID); break; // 切换输入 case R.id.switch_voice_ib: mChatView.dismissMoreMenu(); isInputByKeyBoard = !isInputByKeyBoard; if (isInputByKeyBoard) { mChatView.isKeyBoard(); mChatView.mChatInputEt.requestFocus(); mIsShowMoreMenu = true; mChatView.focusToInput(true); } else { mChatView.notKeyBoard(mConv, mChatAdapter); mIsShowMoreMenu = false; Log.i("ChatController", "setConversation success"); // 关闭软键盘 dismissSoftInput(); } break; case R.id.chat_input_et: mChatView.showMoreMenu(); // mChatView.invisibleMoreMenu(); mIsShowMoreMenu = true; showSoftInput(); break; // 发送文本消息 case R.id.send_msg_btn: String msgContent = mChatView.getChatInput(); mChatView.clearInput(); mChatView.setToBottom(); if (msgContent.equals("")) { return; } TextContent content = new TextContent(msgContent); final Message msg = mConv.createSendMessage(content); msg.setOnSendCompleteCallback( new BasicCallback() { @Override public void gotResult(final int status, String desc) { Log.i("ChatController", "send callback " + status + " desc " + desc); if (status != 0) { mContext.runOnUiThread( new Runnable() { @Override public void run() { HandleResponseCode.onHandle(mContext, status); } }); } // 发送成功或失败都要刷新一次 android.os.Message msg = handler.obtainMessage(); msg.what = UPDATE_CHAT_LISTVIEW; Bundle bundle = new Bundle(); bundle.putString("desc", desc); msg.setData(bundle); msg.sendToTarget(); } }); mChatAdapter.addMsgToList(msg); JMessageClient.sendMessage(msg); break; case R.id.expression_btn: // if (mMoreMenuVisible) { // mChatView.invisibleMoreMenu(); // mMoreMenuVisible = false; // // } break; // 点击添加按钮,弹出更多选项菜单 case R.id.add_file_btn: // 如果在语音输入时点击了添加按钮,则显示菜单并切换到输入框 if (!isInputByKeyBoard) { mChatView.isKeyBoard(); isInputByKeyBoard = true; mChatView.showMoreMenu(); mIsShowMoreMenu = true; mChatView.focusToInput(false); } else { if (mIsShowMoreMenu) { if (mMoreMenuVisible) { mChatView.focusToInput(true); showSoftInput(); mMoreMenuVisible = false; } else { dismissSoftInput(); mChatView.focusToInput(false); mMoreMenuVisible = true; } } else { mChatView.focusToInput(false); mChatView.showMoreMenu(); mIsShowMoreMenu = true; mMoreMenuVisible = true; } } break; // 拍照 case R.id.pick_from_camera_btn: takePhoto(); if (mIsShowMoreMenu) { mChatView.dismissMoreMenu(); dismissSoftInput(); mIsShowMoreMenu = false; } break; case R.id.pick_from_local_btn: if (mIsShowMoreMenu) { mChatView.dismissMoreMenu(); dismissSoftInput(); mIsShowMoreMenu = false; } Intent intent = new Intent(); if (mIsGroup) { intent.putExtra("groupID", mGroupID); } else { intent.putExtra("targetID", mTargetID); } intent.putExtra("isGroup", mIsGroup); mContext.StartPickPictureTotalActivity(intent); break; case R.id.send_location_btn: break; } }
// 处理图片 private void handleImgMsg(final Message msg, final ViewHolder holder, final int position) { final ImageContent imgContent = (ImageContent) msg.getContent(); // 先拿本地缩略图 final String path = imgContent.getLocalThumbnailPath(); // 接收图片 if (msg.getDirect() == MessageDirect.receive) { if (path == null) { // 从服务器上拿缩略图 imgContent.downloadThumbnailImage( msg, new DownloadCompletionCallback() { @Override public void onComplete(int status, String desc, File file) { if (status == 0) { Picasso.with(mContext).load(file).into(holder.picture); } } }); } else { setPictureScale(path, holder.picture); Picasso.with(mContext).load(new File(path)).into(holder.picture); } // 群聊中显示昵称 if (mIsGroup) { holder.displayName.setVisibility(View.VISIBLE); if (TextUtils.isEmpty(msg.getFromUser().getNickname())) { holder.displayName.setText(msg.getFromUser().getUserName()); } else { holder.displayName.setText(msg.getFromUser().getNickname()); } } switch (msg.getStatus()) { case receive_fail: holder.picture.setImageResource(R.drawable.jmui_fetch_failed); break; default: } // 发送图片方,直接加载缩略图 } else { try { setPictureScale(path, holder.picture); Picasso.with(mContext).load(new File(path)).into(holder.picture); } catch (NullPointerException e) { Picasso.with(mContext).load(R.drawable.jmui_picture_not_found).into(holder.picture); } final Animation sendingAnim = AnimationUtils.loadAnimation(mContext, R.anim.jmui_rotate); LinearInterpolator lin = new LinearInterpolator(); sendingAnim.setInterpolator(lin); // 检查状态 switch (msg.getStatus()) { case send_success: holder.sendingIv.clearAnimation(); holder.sendingIv.setVisibility(View.GONE); holder.picture.setAlpha(1.0f); holder.progressTv.setVisibility(View.GONE); holder.resend.setVisibility(View.GONE); break; case send_fail: holder.sendingIv.clearAnimation(); holder.sendingIv.setVisibility(View.GONE); holder.picture.setAlpha(1.0f); holder.progressTv.setVisibility(View.GONE); holder.resend.setVisibility(View.VISIBLE); break; case send_going: sendingImage(holder, sendingAnim, msg); break; default: holder.picture.setAlpha(0.75f); holder.sendingIv.setVisibility(View.VISIBLE); holder.sendingIv.startAnimation(sendingAnim); holder.progressTv.setVisibility(View.VISIBLE); holder.progressTv.setText("0%"); holder.resend.setVisibility(View.GONE); // 从别的界面返回聊天界面,继续发送 if (!mMsgQueue.isEmpty()) { Message message = mMsgQueue.element(); if (message.getId() == msg.getId()) { Log.d(TAG, "Start sending message"); JMessageClient.sendMessage(message); mSendMsgId = message.getId(); sendingImage(holder, sendingAnim, message); } } } // 点击重发按钮,重发图片 holder.resend.setOnClickListener( new OnClickListener() { @Override public void onClick(View arg0) { showResendDialog(holder, sendingAnim, msg); } }); } if (holder.picture != null) { // TODO 点击图片事件 holder.picture.setOnLongClickListener( new OnLongClickListener() { @Override public boolean onLongClick(View v) { String name = msg.getFromUser().getUserName(); OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.copy_msg_btn: break; case R.id.forward_msg_btn: mDialog.dismiss(); break; case R.id.delete_msg_btn: mConv.deleteMessage(msg.getId()); mMsgList.remove(position); notifyDataSetChanged(); mDialog.dismiss(); break; } } }; mDialog = DialogCreator.createLongPressMessageDialog(mContext, name, true, listener); mDialog.show(); mDialog .getWindow() .setLayout((int) (0.8 * mWidth), WindowManager.LayoutParams.WRAP_CONTENT); return true; } }); } }
private void playVoice(final int position, final ViewHolder holder, final boolean isSender) { // 记录播放录音的位置 mPosition = position; Message msg = mMsgList.get(position); if (autoPlay) { mConv.updateMessageExtra(msg, "isReaded", true); holder.readStatus.setVisibility(View.GONE); if (mVoiceAnimation != null) { mVoiceAnimation.stop(); mVoiceAnimation = null; } holder.voice.setImageResource(R.anim.jmui_voice_receive); mVoiceAnimation = (AnimationDrawable) holder.voice.getDrawable(); } try { mp.reset(); VoiceContent vc = (VoiceContent) msg.getContent(); Log.i(TAG, "content.getLocalPath:" + vc.getLocalPath()); mFIS = new FileInputStream(vc.getLocalPath()); mFD = mFIS.getFD(); mp.setDataSource(mFD); if (mIsEarPhoneOn) { mp.setAudioStreamType(AudioManager.STREAM_VOICE_CALL); } else { mp.setAudioStreamType(AudioManager.STREAM_MUSIC); } mp.prepare(); mp.setOnPreparedListener( new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mVoiceAnimation.start(); mp.start(); } }); mp.setOnCompletionListener( new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mVoiceAnimation.stop(); mp.reset(); mSetData = false; if (isSender) { holder.voice.setImageResource(R.drawable.jmui_send_3); } else { holder.voice.setImageResource(R.drawable.jmui_receive_3); } if (autoPlay) { int curCount = mIndexList.indexOf(position); Log.d(TAG, "curCount = " + curCount); if (curCount + 1 >= mIndexList.size()) { nextPlayPosition = -1; autoPlay = false; } else { nextPlayPosition = mIndexList.get(curCount + 1); notifyDataSetChanged(); } mIndexList.remove(curCount); } } }); } catch (FileNotFoundException e) { Toast.makeText( mContext, mContext.getString(R.string.file_not_found_toast), Toast.LENGTH_SHORT) .show(); } catch (IOException e) { Toast.makeText( mActivity, mContext.getString(R.string.file_not_found_toast), Toast.LENGTH_SHORT) .show(); } finally { try { if (mFIS != null) { mFIS.close(); } } catch (IOException e) { e.printStackTrace(); } } }
@Override public View getView(final int position, View convertView, ViewGroup parent) { final Message msg = mMsgList.get(position); final UserInfo userInfo = msg.getFromUser(); final ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = createViewByType(msg, position); switch (msg.getContentType()) { case text: holder.headIcon = (CircleImageView) convertView.findViewById(R.id.avatar_iv); holder.displayName = (TextView) convertView.findViewById(R.id.display_name_tv); holder.txtContent = (TextView) convertView.findViewById(R.id.msg_content); holder.sendingIv = (ImageView) convertView.findViewById(R.id.sending_iv); holder.resend = (ImageButton) convertView.findViewById(R.id.fail_resend_ib); holder.groupChange = (TextView) convertView.findViewById(R.id.group_content); break; case image: holder.headIcon = (CircleImageView) convertView.findViewById(R.id.avatar_iv); holder.displayName = (TextView) convertView.findViewById(R.id.display_name_tv); holder.picture = (ImageView) convertView.findViewById(R.id.picture_iv); holder.sendingIv = (ImageView) convertView.findViewById(R.id.sending_iv); holder.progressTv = (TextView) convertView.findViewById((R.id.progress_tv)); holder.resend = (ImageButton) convertView.findViewById(R.id.fail_resend_ib); break; case voice: holder.headIcon = (CircleImageView) convertView.findViewById(R.id.avatar_iv); holder.displayName = (TextView) convertView.findViewById(R.id.display_name_tv); holder.txtContent = (TextView) convertView.findViewById(R.id.msg_content); holder.voice = ((ImageView) convertView.findViewById(R.id.voice_iv)); holder.sendingIv = (ImageView) convertView.findViewById(R.id.sending_iv); holder.voiceLength = (TextView) convertView.findViewById(R.id.voice_length_tv); holder.readStatus = (ImageView) convertView.findViewById(R.id.read_status_iv); holder.resend = (ImageButton) convertView.findViewById(R.id.fail_resend_ib); break; case location: holder.headIcon = (CircleImageView) convertView.findViewById(R.id.avatar_iv); holder.displayName = (TextView) convertView.findViewById(R.id.display_name_tv); holder.txtContent = (TextView) convertView.findViewById(R.id.msg_content); holder.sendingIv = (ImageView) convertView.findViewById(R.id.sending_iv); holder.resend = (ImageButton) convertView.findViewById(R.id.fail_resend_ib); break; case eventNotification: holder.groupChange = (TextView) convertView.findViewById(R.id.group_content); break; default: holder.groupChange = (TextView) convertView.findViewById(R.id.group_content); } convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // 显示时间 TextView msgTime = (TextView) convertView.findViewById(R.id.send_time_txt); long nowDate = msg.getCreateTime(); if (mOffset == 18) { if (position == 0 || position % 18 == 0) { TimeFormat timeFormat = new TimeFormat(mContext, nowDate); msgTime.setText(timeFormat.getDetailTime()); msgTime.setVisibility(View.VISIBLE); } else { long lastDate = mMsgList.get(position - 1).getCreateTime(); // 如果两条消息之间的间隔超过十分钟则显示时间 if (nowDate - lastDate > 600000) { TimeFormat timeFormat = new TimeFormat(mContext, nowDate); msgTime.setText(timeFormat.getDetailTime()); msgTime.setVisibility(View.VISIBLE); } else { msgTime.setVisibility(View.GONE); } } } else { if (position == 0 || position == mOffset || (position - mOffset) % 18 == 0) { TimeFormat timeFormat = new TimeFormat(mContext, nowDate); msgTime.setText(timeFormat.getDetailTime()); msgTime.setVisibility(View.VISIBLE); } else { long lastDate = mMsgList.get(position - 1).getCreateTime(); // 如果两条消息之间的间隔超过十分钟则显示时间 if (nowDate - lastDate > 600000) { TimeFormat timeFormat = new TimeFormat(mContext, nowDate); msgTime.setText(timeFormat.getDetailTime()); msgTime.setVisibility(View.VISIBLE); } else { msgTime.setVisibility(View.GONE); } } } // 显示头像 if (holder.headIcon != null) { if (userInfo != null && !TextUtils.isEmpty(userInfo.getAvatar())) { userInfo.getAvatarBitmap( new GetAvatarBitmapCallback() { @Override public void gotResult(int status, String desc, Bitmap bitmap) { if (status == 0) { holder.headIcon.setImageBitmap(bitmap); } else { holder.headIcon.setImageResource(R.drawable.jmui_head_icon); HandleResponseCode.onHandle(mContext, status, false); } } }); } else { holder.headIcon.setImageResource(R.drawable.jmui_head_icon); } // TODO 点击头像事件 } OnLongClickListener longClickListener = new OnLongClickListener() { @Override public boolean onLongClick(View arg0) { // 长按文本弹出菜单 String name = userInfo.getUserName(); OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.copy_msg_btn: if (msg.getContentType() == ContentType.text) { final String content = ((TextContent) msg.getContent()).getText(); if (Build.VERSION.SDK_INT > 11) { ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(mContext.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Simple text", content); clipboard.setPrimaryClip(clip); } else { ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(mContext.CLIPBOARD_SERVICE); clipboard.setText(content); // 设置Clipboard 的内容 if (clipboard.hasText()) { clipboard.getText(); } } Toast.makeText( mContext, mContext.getString(R.string.copy_toast), Toast.LENGTH_SHORT) .show(); mDialog.dismiss(); } break; case R.id.forward_msg_btn: mDialog.dismiss(); break; case R.id.delete_msg_btn: mConv.deleteMessage(msg.getId()); mMsgList.remove(position); notifyDataSetChanged(); mDialog.dismiss(); break; } } }; boolean hide = msg.getContentType() == ContentType.voice; mDialog = DialogCreator.createLongPressMessageDialog(mContext, name, hide, listener); mDialog.show(); mDialog .getWindow() .setLayout((int) (0.8 * mWidth), WindowManager.LayoutParams.WRAP_CONTENT); return true; } }; switch (msg.getContentType()) { case text: handleTextMsg(msg, holder, longClickListener); break; case image: handleImgMsg(msg, holder, position); break; case voice: handleVoiceMsg(msg, holder, position, longClickListener); break; case eventNotification: handleGroupChangeMsg(msg, holder, msgTime); break; default: handleCustomMsg(msg, holder); } return convertView; }