/** * 当应用在前台时,如果当前消息不是属于当前会话,在状态栏提示一下 如果不需要,注释掉即可 * * @param message */ protected void notifyNewMessage(EMMessage message, String nick) { // 如果是设置了不提醒只显示数目的群组(这个是app里保存这个数据的,demo里不做判断) // 以及设置了setShowNotificationInbackgroup:false(设为false后,后台时sdk也发送广播) if (!EasyUtils.isAppRunningForeground(this)) { return; } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(getApplicationInfo().icon) .setWhen(System.currentTimeMillis()) .setAutoCancel(false); String ticker = CommonUtils.getMessageDigest(message, this); String st = getResources().getString(R.string.expression); if (message.getType() == EMMessage.Type.TXT) ticker = ticker.replaceAll("\\[.{2,3}\\]", st); // 设置状态栏提示 mBuilder.setTicker(nick + ": " + ticker); mBuilder.setContentText("查看新的未读消息"); mBuilder.setContentTitle(message.getStringAttribute(Const.Easemob.FROM_USER_NICK, "新消息")); // 必须设置pendingintent,否则在2.3的机器上会有bug Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(Const.Intent.HX_NTF_TO_MAIN, true); PendingIntent pendingIntent = PendingIntent.getActivity(this, notifiId, intent, PendingIntent.FLAG_ONE_SHOT); mBuilder.setContentIntent(pendingIntent); Notification notification = mBuilder.build(); notificationManager.notify(notifiId, notification); // notificationManager.cancel(notifiId); }
private void refreshLike(String like) { if (like != null) { try { JSONObject jsonObject = new JSONObject(like); String state = jsonObject.getString(JsonString.Return.STATE); if (state.equals("20002")) { // 对方已经Like过我 ToastUtil.prompt(this, "双方相互Like,你们已经是好友了"); Intent intent = new Intent(IntentString.Receiver.NEW_FRIEND); sendBroadcast(intent); EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT); TextMessageBody txtBody = new TextMessageBody("我们已经是好友了,可以开始聊天了"); message.addBody(txtBody); message.setReceipt(person.getId()); EMConversation conversation = EMChatManager.getInstance().getConversation(person.getId()); conversation.addMessage(message); finish(); } else if (state.equals("10004")) { ToastUtil.longPrompt(this, "检测到您的头像不是真人头像,Like操作无效"); } else { ToastUtil.prompt(this, "Like操作失败!"); } } catch (JSONException e) { e.printStackTrace(); } } else { ToastUtil.noNet(this); } }
@Override public void onEvent(EMNotifierEvent event) { switch (event.getEvent()) { case EventNewMessage: { EMMessage message = (EMMessage) event.getData(); String userId = null; userId = message.getFrom(); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(getApplicationContext().getApplicationInfo().icon) .setWhen(System.currentTimeMillis()) .setContentTitle("有新消息了!") .setContentText("A+") .setAutoCancel(true); Intent resultIntent = new Intent(this, ChatActivity.class); resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); resultIntent.putExtra("notification", true); resultIntent.putExtra("easemobId", userId); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(ChatActivity.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(0, mBuilder.build()); } } }
@Override public boolean onNewMessage(EMMessage message) { if (stoped) { return false; } EMUserInfo userinfo = EMUserInfo.createEMUserInfo(message); PendingIntent pendingIntent = null; if (message.getChatType() == EMMessage.ChatType.Chat) { String toUserName = message.getChatType() == EMMessage.ChatType.Chat ? message.getFrom() : message.getTo(); Intent intent = new Intent(self, SingleChatActivity.class) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .putExtra(EaseConstant.EXTRA_USER_ID, toUserName); pendingIntent = PendingIntent.getActivity(self, 0, intent, PendingIntent.FLAG_ONE_SHOT); NotificationHelper.showNotification( self, EMChatHelper.EMCHAT_NEW_MESSAGE_NOTIFY_ID, userinfo.getUserNick() + "发来一条新信息", EMMessageHelper.getMessageBody(message), pendingIntent); } else if (message.getChatType() == EMMessage.ChatType.ChatRoom) { return true; } return true; }
@Override public void onEvent(EMNotifierEvent event) { switch (event.getEvent()) { case EventNewMessage: // 普通消息 { EMMessage message = (EMMessage) event.getData(); try { showLogD("MESSAGE " + message.getStringAttribute("groupName")); } catch (EaseMobException e) { e.printStackTrace(); } // 提示新消息 HXSDKHelper.getInstance().getNotifier().onNewMsg(message); refreshUI(); break; } case EventOfflineMessage: { refreshUI(); break; } case EventConversationListChanged: { refreshUI(); break; } default: break; } }
/** * 发送通知栏提示 This can be override by subclass to provide customer implementation * * @param messages * @param isForeground */ protected void sendNotification(List<EMMessage> messages, boolean isForeground) { for (EMMessage message : messages) { if (!isForeground) { notificationNum++; fromUsers.add(message.getFrom()); } } sendNotification(messages.get(messages.size() - 1), isForeground, false); }
public void playVoice(String filePath) { if (!(new File(filePath).exists())) { return; } AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE); mediaPlayer = new MediaPlayer(); if (EMChatManager.getInstance().getChatOptions().getUseSpeaker()) { audioManager.setMode(AudioManager.MODE_NORMAL); audioManager.setSpeakerphoneOn(true); mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING); } else { audioManager.setSpeakerphoneOn(false); // 关闭扬声器 // 把声音设定成Earpiece(听筒)出来,设定为正在通话中 audioManager.setMode(AudioManager.MODE_IN_CALL); mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL); } try { mediaPlayer.setDataSource(filePath); mediaPlayer.prepare(); mediaPlayer.setOnCompletionListener( new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mediaPlayer.release(); mediaPlayer = null; stopPlayVoice(); // stop animation } }); isPlaying = true; currentPlayListener = this; currentMessage = message; mediaPlayer.start(); showAnimation(); try { // 如果是接收的消息 if (!message.isAcked && message.direct == EMMessage.Direct.RECEIVE) { message.isAcked = true; if (iv_read_status != null && iv_read_status.getVisibility() == View.VISIBLE) { // 隐藏自己未播放这条语音消息的标志 iv_read_status.setVisibility(View.INVISIBLE); EMChatDB.getInstance().updateMessageAck(message.getMsgId(), true); } // 告知对方已读这条消息 if (chatType != ChatType.GroupChat) EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId()); } } catch (Exception e) { message.isAcked = false; } } catch (Exception e) { } }
public void onReceive(Context context, Intent intent) { String msgid = intent.getStringExtra("msgid"); String from = intent.getStringExtra("from"); EMConversation conversation = EMChatManager.getInstance().getConversation(from); if (conversation != null) { EMMessage msg = conversation.getMessage(msgid); if (msg != null) { msg.isAcked = true; } } abortBroadcast(); }
/** * 保存通话消息记录 * * @param type 0:音频,1:视频 */ protected void saveCallRecord(int type) { EMMessage message = null; TextMessageBody txtBody = null; if (!isInComingCall) { // 打出去的通话 message = EMMessage.createSendMessage(EMMessage.Type.TXT); message.setReceipt(username); } else { message = EMMessage.createReceiveMessage(EMMessage.Type.TXT); message.setFrom(username); } String st1 = getResources().getString(R.string.call_duration); String st2 = getResources().getString(R.string.Refused); String st3 = getResources().getString(R.string.The_other_party_has_refused_to); String st4 = getResources().getString(R.string.The_other_is_not_online); String st5 = getResources().getString(R.string.The_other_is_on_the_phone); String st6 = getResources().getString(R.string.The_other_party_did_not_answer); String st7 = getResources().getString(R.string.did_not_answer); String st8 = getResources().getString(R.string.Has_been_cancelled); switch (callingState) { case NORMAL: txtBody = new TextMessageBody(st1 + callDruationText); break; case REFUESD: txtBody = new TextMessageBody(st2); break; case BEREFUESD: txtBody = new TextMessageBody(st3); break; case OFFLINE: txtBody = new TextMessageBody(st4); break; case BUSY: txtBody = new TextMessageBody(st5); break; case NORESPONSE: txtBody = new TextMessageBody(st6); break; case UNANSWERED: txtBody = new TextMessageBody(st7); break; default: txtBody = new TextMessageBody(st8); break; } // 设置扩展属性 if (type == 0) message.setAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, true); else message.setAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, true); // 设置消息body message.addBody(txtBody); message.setMsgId(msgid); // 保存 EMChatManager.getInstance().saveMessage(message, false); }
public EaseChatRowVoicePlayClickListener( EMMessage message, ImageView v, ImageView iv_read_status, BaseAdapter adapter, Activity context) { this.message = message; voiceBody = (VoiceMessageBody) message.getBody(); this.iv_read_status = iv_read_status; this.adapter = adapter; voiceIconView = v; this.activity = context; this.chatType = message.getChatType(); }
/** * @param message * @param v * @param iv_read_status * @param context * @param activity * @param user * @param chatType */ public VoicePlayClickListener( EMMessage message, ImageView v, ImageView iv_read_status, BaseAdapter adapter, Activity activity, String username) { this.message = message; voiceBody = (VoiceMessageBody) message.getBody(); this.iv_read_status = iv_read_status; this.adapter = adapter; voiceIconView = v; this.activity = activity; this.chatType = message.getChatType(); }
/** * @param message * @param v * @param iv_read_status * @param context * @param activity * @param user * @param chatType */ public VoicePlayClickListener( EMMessage message, ImageView v, ImageView iv_read_status, Context context, Activity activity, String username) { this.message = message; voiceBody = (VoiceMessageBody) message.getBody(); this.iv_read_status = iv_read_status; this.context = context; voiceIconView = v; this.activity = activity; this.username = username; this.chatType = message.getChatType(); }
@SuppressWarnings("unused") @Override public void onReceive(Context context, Intent intent) { abortBroadcast(); EMLog.d("收到消息", "收到透传消息"); // 获取cmd message对象 String msgId = intent.getStringExtra("msgid"); EMMessage message = intent.getParcelableExtra("message"); // 获取消息body CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody(); String action = cmdMsgBody.action; // 获取自定义action // 获取扩展属性 此处省略 // message.getStringAttribute(""); EMLog.d("收到消息", String.format("透传消息:action:%s,message:%s", action, message.toString())); // String st9 = getResources().getString(R.string.receive_the_passthrough); // Toast.makeText(MainActivity.this, st9+action, Toast.LENGTH_SHORT).show(); }
@Override public void onReceive(Context context, Intent intent) { // 获取cmd message对象 String msgId = intent.getStringExtra("msgid"); EMMessage message = intent.getParcelableExtra("message"); // 获取消息body CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody(); String aciton = cmdMsgBody.action; // 获取自定义action // 获取扩展属性 try { String attr = message.getStringAttribute("photoUrl"); ImageLoader.getInstance().getMemoryCache().remove(attr); ImageLoader.getInstance().getDiskCache().remove(attr); showToast("清除缓存"); System.out.println("清除缓存"); } catch (EaseMobException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public boolean isRobotMenuMessage(EMMessage message) { try { JSONObject jsonObj = message.getJSONObjectAttribute(Constant.MESSAGE_ATTR_ROBOT_MSGTYPE); if (jsonObj.has("choice")) { return true; } } catch (Exception e) { } return false; }
@Override public void onReceive(Context context, Intent intent) { abortBroadcast(); String msgid = intent.getStringExtra("msgid"); String from = intent.getStringExtra("from"); EMConversation conversation = EMChatManager.getInstance().getConversation(from); if (conversation != null) { // 把message设为已读 EMMessage msg = conversation.getMessage(msgid); if (msg != null) { // 2014-11-5 修复在某些机器上,在聊天页面对方发送已读回执时不立即显示已读的bug if (ChatActivity.activityInstance != null) { if (msg.getChatType() == ChatType.Chat) { if (from.equals(ChatActivity.activityInstance.getToChatUsername())) return; } } msg.isAcked = true; } } }
public String getRobotMenuMessageDigest(EMMessage message) { String title = ""; try { JSONObject jsonObj = message.getJSONObjectAttribute(Constant.MESSAGE_ATTR_ROBOT_MSGTYPE); if (jsonObj.has("choice")) { JSONObject jsonChoice = jsonObj.getJSONObject("choice"); title = jsonChoice.getString("title"); } } catch (Exception e) { } return title; }
@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_chatmsg, null); username = (TextView) convertView.findViewById(R.id.tv_chatusername); username.setText(message.getFrom()); } } else { if (message.getType() == EMMessage.Type.TXT) { convertView = LayoutInflater.from(mcontext).inflate(R.layout.item_chatmsg2, null); username = (TextView) convertView.findViewById(R.id.tv_chatusername); // username.setText(message.getFrom()); } } msg = (TextView) convertView.findViewById(R.id.tv_chatmsg); msg.setText(body.getMessage()); return convertView; }
public static void EaseBlackUser(String action, String easeName) { EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD); CmdMessageBody cmdBody = new CmdMessageBody(action); cmdMsg.setReceipt(easeName); cmdMsg.addBody(cmdBody); EMChatManager.getInstance() .sendMessage( cmdMsg, new EMCallBack() { @Override public void onSuccess() { Log.e("发送请求视频的透传发送成功", ""); } @Override public void onError(int i, String s) { Log.e("发送请求视频的透传发送失败", ""); } @Override public void onProgress(int i, String s) {} }); }
@Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub LogUtil.d("聊天界面收到消息", "消息"); int length = mAdapter.getCount(); String msgid = intent.getStringExtra("msgid"); String username = intent.getStringExtra("from"); EMMessage message = EMChatManager.getInstance().getMessage(msgid); JSONObject jsonObject; // try { // if(propellingMessageTurnTo.isAdv(message)){ // propellingMessageTurnTo.turnToActivity(message); // } // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } if (message.getChatType() != ChatType.GroupChat && username.equals(hxusernameString)) { abortBroadcast(); Message message2 = new Message(); message2.what = 1; handler.sendMessage(message2); mAdapter.notifyDataSetChanged(); lv.setSelection(lv.getCount() - 1); LogUtil.d("长度", length + "ddd" + mAdapter.getCount()); // 设置消息已读 EMConversation conversation = EMChatManager.getInstance().getConversation(username); conversation.resetUnreadMsgCount(); } else { unRead.setVisibility(View.VISIBLE); unReadCount++; unRead.setText("聊天(" + unReadCount + ")"); return; } }
@Override public void onClick(View v) { if (isPlaying) { currentPlayListener.stopPlayVoice(); if (currentMessage != null && currentMessage.hashCode() == message.hashCode()) { currentMessage = null; return; } } if (message.direct == EMMessage.Direct.SEND) { // for sent msg, we will try to play the voice file directly playVoice(voiceBody.getLocalUrl()); } else { if (message.status == EMMessage.Status.SUCCESS) { File file = new File(voiceBody.getLocalUrl()); if (file.exists() && file.isFile()) playVoice(voiceBody.getLocalUrl()); else System.err.println("file not exist"); } else if (message.status == EMMessage.Status.INPROGRESS) { Toast.makeText(context, "正在下载语音,稍后点击", Toast.LENGTH_SHORT).show(); } else if (message.status == EMMessage.Status.FAIL) { Toast.makeText(context, "正在下载语音,稍后点击", Toast.LENGTH_SHORT).show(); new Thread( new Runnable() { @Override public void run() { EMChatManager.getInstance().asyncFetchMessage(message); } }) .start(); } } }
@Override public void onReceive(Context context, Intent intent) { // 主页面收到消息后,主要为了提示未读,实际消息内容需要到chat页面查看 String from = intent.getStringExtra("from"); // 消息id String msgId = intent.getStringExtra("msgid"); EMMessage message = EMChatManager.getInstance().getMessage(msgId); // 2014-10-22 修复在某些机器上,在聊天页面对方发消息过来时不立即显示内容的bug if (ChatActivity.activityInstance != null) { if (message.getChatType() == ChatType.GroupChat) { if (message.getTo().equals(ChatActivity.activityInstance.getToChatUsername())) return; } else { if (from.equals(ChatActivity.activityInstance.getToChatUsername())) return; } } // 注销广播接收者,否则在ChatActivity中会收到这个广播 abortBroadcast(); notifyNewMessage(message); // 刷新bottom bar消息未读 // updateUnreadLabel(); }
/** * 根据消息内容和消息类型获取消息内容提示 * * @param message * @param context * @return */ private String getMessageDigest(EMMessage message, Context context) { String digest = ""; switch (message.getType()) { case LOCATION: // 位置消息 if (message.direct == EMMessage.Direct.RECEIVE) { digest = getStrng(context, R.string.location_recv); String name = message.getFrom(); if (GloableParams.UserInfos != null) { User user = GloableParams.Users.get(message.getFrom()); if (null != user.getUserName()) name = user.getUserName(); } digest = String.format(digest, message.getFrom()); return digest; } else { digest = getStrng(context, R.string.location_prefix); } break; case IMAGE: // 图片消息 ImageMessageBody imageBody = (ImageMessageBody) message.getBody(); digest = getStrng(context, R.string.picture) + imageBody.getFileName(); break; case VOICE: // 语音消息 digest = getStrng(context, R.string.voice_msg); break; case VIDEO: // 视频消息 digest = getStrng(context, R.string.video); break; case TXT: // 文本消息 if (!message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) { TextMessageBody txtBody = (TextMessageBody) message.getBody(); digest = txtBody.getMessage(); } else { TextMessageBody txtBody = (TextMessageBody) message.getBody(); digest = getStrng(context, R.string.voice_call) + txtBody.getMessage(); } break; case FILE: // 普通文件消息 digest = getStrng(context, R.string.file); break; default: System.err.println("error, unknow type"); return ""; } return digest; }
@Override public void onClick(View v) { String st = activity.getResources().getString(R.string.Is_download_voice_click_later); if (isPlaying) { if (((ChatActivity) activity).playMsgId != null && ((ChatActivity) activity).playMsgId.equals(message.getMsgId())) { currentPlayListener.stopPlayVoice(); return; } currentPlayListener.stopPlayVoice(); } if (message.direct == EMMessage.Direct.SEND) { // for sent msg, we will try to play the voice file directly playVoice(voiceBody.getLocalUrl()); } else { if (message.status == EMMessage.Status.SUCCESS) { File file = new File(voiceBody.getLocalUrl()); if (file.exists() && file.isFile()) playVoice(voiceBody.getLocalUrl()); else EMLog.e(TAG, "file not exist"); } else if (message.status == EMMessage.Status.INPROGRESS) { String s = new String(); Toast.makeText(activity, st, Toast.LENGTH_SHORT).show(); } else if (message.status == EMMessage.Status.FAIL) { Toast.makeText(activity, st, Toast.LENGTH_SHORT).show(); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { EMChatManager.getInstance().asyncFetchMessage(message); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); adapter.notifyDataSetChanged(); } }.execute(); } } }
/** * 根据消息内容和消息类型获取消息内容提示 * * @param message * @param context * @return */ private String getMessageDigest(EMMessage message, Context context) { String digest = ""; switch (message.getType()) { case LOCATION: // 位置消息 if (message.direct == EMMessage.Direct.RECEIVE) { // 从sdk中提到了ui中,使用更简单不犯错的获取string的方法 // digest = EasyUtils.getAppResourceString(context, // "location_recv"); digest = getStrng(context, R.string.location_recv); digest = String.format(digest, message.getFrom()); return digest; } else { // digest = EasyUtils.getAppResourceString(context, // "location_prefix"); digest = getStrng(context, R.string.location_prefix); } break; case IMAGE: // 图片消息 ImageMessageBody imageBody = (ImageMessageBody) message.getBody(); digest = getStrng(context, R.string.picture) + imageBody.getFileName(); break; case VOICE: // 语音消息 digest = getStrng(context, R.string.voice); break; case VIDEO: // 视频消息 digest = getStrng(context, R.string.video); break; case TXT: // 文本消息 if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).isRobotMenuMessage(message)) { digest = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getRobotMenuMessageDigest(message); } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) { TextMessageBody txtBody = (TextMessageBody) message.getBody(); digest = getStrng(context, R.string.voice_call) + txtBody.getMessage(); } else { TextMessageBody txtBody = (TextMessageBody) message.getBody(); digest = txtBody.getMessage(); } break; case FILE: // 普通文件消息 digest = getStrng(context, R.string.file); break; default: EMLog.e(TAG, "unknow type"); return ""; } return digest; }
/** * 当应用在前台时,如果当前消息不是属于当前会话,在状态栏提示一下 如果不需要,注释掉即可 * * @param message */ public void notifyNewMessage(EMMessage message) { // 如果是设置了不提醒只显示数目的群组(这个是app里保存这个数据的,demo里不做判断) // 以及设置了setShowNotificationInbackgroup:false(设为false后,后台时sdk也发送广播) if (!EasyUtils.isAppRunningForeground(this)) { return; } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.zhxy_logo) .setContentTitle("新消息") .setWhen(System.currentTimeMillis()) .setAutoCancel(true); String ticker = CommonUtils.getMessageDigest(message, this); String st = getResources().getString(R.string.expression); if (message.getType() == Type.TXT) ticker = ticker.replaceAll("\\[.{2,3}\\]", st); // 设置状态栏提示 mBuilder.setTicker(message.getFrom() + ": " + ticker); // 必须设置pendingintent,否则在2.3的机器上会有bug Intent intent = new Intent(this, ChatActivity.class); // 程序内 跳转 单聊 if (message.getChatType() == ChatType.Chat) { intent.putExtra(Constants.TEL, message.getFrom()); intent.putExtra(Constants.USNAME, message.getUserName()); Log.e("TAG", "收到的手机号 = " + message.getFrom()); Log.e("得到的用户名为:", message.getUserName()); } // 程序内 跳转 群聊 if (message.getChatType() == ChatType.GroupChat) { intent.putExtra(Constants.TEL, message.getTo()); intent.putExtra("chatType", Constants.CHATTYPE_GROUP); intent.putExtra( Constants.CLASS_SHORT_NAME, SharedPreferencesUtil.getClassShortName(getApplicationContext())); Log.e( "TAG", "收到的群组id = " + message.getTo() + "传递的 班级名称 = " + SharedPreferencesUtil.getClassShortName(getApplicationContext())); } intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, notifiId, intent, PendingIntent.FLAG_ONE_SHOT); mBuilder.setContentIntent(pendingIntent); Notification notification = mBuilder.build(); notificationManager.notify(notifiId, notification); Intent intent2 = new Intent(); intent2.setAction(Constants.AREA_UNREAD); intent2.putExtra(Constants.MSG_FROM, message.getFrom()); sendOrderedBroadcast(intent2, null); }
/** * 发送通知栏提示 This can be override by subclass to provide customer implementation * * @param message */ protected void sendNotification(EMMessage message, boolean isForeground, boolean numIncrease) { String username = message.getFrom(); try { String notifyText = username + " "; switch (message.getType()) { case TXT: notifyText += msgs[0]; break; case IMAGE: notifyText += msgs[1]; break; case VOICE: notifyText += msgs[2]; break; case LOCATION: notifyText += msgs[3]; break; case VIDEO: notifyText += msgs[4]; break; case FILE: notifyText += msgs[5]; break; } PackageManager packageManager = appContext.getPackageManager(); String appname = (String) packageManager.getApplicationLabel(appContext.getApplicationInfo()); // notification titile String contentTitle = appname; if (notificationInfoProvider != null) { String customNotifyText = notificationInfoProvider.getDisplayedText(message); String customCotentTitle = notificationInfoProvider.getTitle(message); if (customNotifyText != null) { // 设置自定义的状态栏提示内容 notifyText = customNotifyText; } if (customCotentTitle != null) { // 设置自定义的通知栏标题 contentTitle = customCotentTitle; } } // create and send notificaiton NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext) .setSmallIcon(appContext.getApplicationInfo().icon) .setWhen(System.currentTimeMillis()) .setAutoCancel(true); Intent msgIntent = appContext.getPackageManager().getLaunchIntentForPackage(packageName); if (notificationInfoProvider != null) { // 设置自定义的notification点击跳转intent msgIntent = notificationInfoProvider.getLaunchIntent(message); } PendingIntent pendingIntent = PendingIntent.getActivity( appContext, notifyID, msgIntent, PendingIntent.FLAG_UPDATE_CURRENT); if (numIncrease) { // prepare latest event info section if (!isForeground) { notificationNum++; fromUsers.add(message.getFrom()); } } int fromUsersNum = fromUsers.size(); String summaryBody = msgs[6] .replaceFirst("%1", Integer.toString(fromUsersNum)) .replaceFirst("%2", Integer.toString(notificationNum)); if (notificationInfoProvider != null) { // lastest text String customSummaryBody = notificationInfoProvider.getLatestText(message, fromUsersNum, notificationNum); if (customSummaryBody != null) { summaryBody = customSummaryBody; } // small icon int smallIcon = notificationInfoProvider.getSmallIcon(message); if (smallIcon != 0) { mBuilder.setSmallIcon(smallIcon); } } mBuilder.setContentTitle(contentTitle); mBuilder.setTicker(notifyText); mBuilder.setContentText(summaryBody); mBuilder.setContentIntent(pendingIntent); // mBuilder.setNumber(notificationNum); Notification notification = mBuilder.build(); if (isForeground) { notificationManager.notify(foregroundNotifyID, notification); notificationManager.cancel(foregroundNotifyID); } else { notificationManager.notify(notifyID, notification); } } catch (Exception e) { e.printStackTrace(); } }
@Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.row_chat_history, parent, false); } ViewHolder holder = (ViewHolder) convertView.getTag(); if (holder == null) { holder = new ViewHolder(); holder.name = (TextView) convertView.findViewById(R.id.name); holder.unreadLabel = (TextView) convertView.findViewById(R.id.unread_msg_number); holder.message = (TextView) convertView.findViewById(R.id.message); holder.time = (TextView) convertView.findViewById(R.id.time); holder.avatar = (ImageView) convertView.findViewById(R.id.avatar); holder.msgState = convertView.findViewById(R.id.msg_state); holder.list_item_layout = (RelativeLayout) convertView.findViewById(R.id.list_item_layout); convertView.setTag(holder); } if (position % 2 == 0) { holder.list_item_layout.setBackgroundResource(R.drawable.mm_listitem); } else { holder.list_item_layout.setBackgroundResource(R.drawable.mm_listitem_grey); } // 获取与此用户/群组的会话 EMConversation conversation = getItem(position); // 获取用户username或者群组groupid String username = conversation.getUserName(); if (conversation.getType() == EMConversationType.GroupChat) { // 群聊消息,显示群聊头像 holder.avatar.setImageResource(R.drawable.group_icon); EMGroup group = EMGroupManager.getInstance().getGroup(username); holder.name.setText(group != null ? group.getGroupName() : username); } else if (conversation.getType() == EMConversationType.ChatRoom) { holder.avatar.setImageResource(R.drawable.group_icon); EMChatRoom room = EMChatManager.getInstance().getChatRoom(username); holder.name.setText( room != null && !TextUtils.isEmpty(room.getName()) ? room.getName() : username); } else { UserUtils.setUserAvatar(getContext(), username, holder.avatar); if (username.equals(Constant.GROUP_USERNAME)) { holder.name.setText("群聊"); } else if (username.equals(Constant.NEW_FRIENDS_USERNAME)) { holder.name.setText("申请与通知"); } Map<String, RobotUser> robotMap = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getRobotList(); if (robotMap != null && robotMap.containsKey(username)) { String nick = robotMap.get(username).getNick(); if (!TextUtils.isEmpty(nick)) { holder.name.setText(nick); } else { holder.name.setText(username); } } else { UserUtils.setUserNick(username, holder.name); } } if (conversation.getUnreadMsgCount() > 0) { // 显示与此用户的消息未读数 holder.unreadLabel.setText(String.valueOf(conversation.getUnreadMsgCount())); holder.unreadLabel.setVisibility(View.VISIBLE); } else { holder.unreadLabel.setVisibility(View.INVISIBLE); } if (conversation.getMsgCount() != 0) { // 把最后一条消息的内容作为item的message内容 EMMessage lastMessage = conversation.getLastMessage(); holder.message.setText( SmileUtils.getSmiledText( getContext(), getMessageDigest(lastMessage, (this.getContext()))), BufferType.SPANNABLE); holder.time.setText(DateUtils.getTimestampString(new Date(lastMessage.getMsgTime()))); if (lastMessage.direct == EMMessage.Direct.SEND && lastMessage.status == EMMessage.Status.FAIL) { holder.msgState.setVisibility(View.VISIBLE); } else { holder.msgState.setVisibility(View.GONE); } } return convertView; }
@Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.layout_item_msg, parent, false); } ImageView img_avar = ViewHolder.get(convertView, R.id.contactitem_avatar_iv); TextView txt_name = ViewHolder.get(convertView, R.id.txt_name); TextView txt_state = ViewHolder.get(convertView, R.id.txt_state); TextView txt_del = ViewHolder.get(convertView, R.id.txt_del); TextView txt_content = ViewHolder.get(convertView, R.id.txt_content); TextView txt_time = ViewHolder.get(convertView, R.id.txt_time); TextView unreadLabel = ViewHolder.get(convertView, R.id.unread_msg_number); SwipeLayout swipe = ViewHolder.get(convertView, R.id.swipe); if (PublicMsg != null && position == 0) { txt_name.setText("订阅号"); img_avar.setImageResource(R.drawable.icon_public); txt_time.setText(PublicMsg.getTime()); txt_content.setText(PublicMsg.getContent()); unreadLabel.setText("3"); unreadLabel.setVisibility(View.VISIBLE); swipe.setSwipeEnabled(false); } else { swipe.setSwipeEnabled(true); // 获取与此用户/群组的会话 final EMConversation conversation = conversationList.get(position); // 获取用户username或者群组groupid ChatID = conversation.getUserName(); txt_del.setTag(ChatID); if (conversation.isGroup()) { GroupInfo info = GloableParams.GroupInfos.get(ChatID); if (info != null) { txt_name.setText(info.getGroup_name()); img_avar.setImageResource(R.drawable.defult_group); // initGroupInfo(img_avar, txt_name);// 获取群组信息 } } else { User user = GloableParams.Users.get(ChatID); if (user != null) { txt_name.setText(user.getUserName()); // initUserInfo(img_avar, txt_name);// 获取用户信息 } } if (conversation.getUnreadMsgCount() > 0) { // 显示与此用户的消息未读数 unreadLabel.setText(String.valueOf(conversation.getUnreadMsgCount())); unreadLabel.setVisibility(View.VISIBLE); } else { unreadLabel.setVisibility(View.INVISIBLE); } if (conversation.getMsgCount() != 0) { // 把最后一条消息的内容作为item的message内容 EMMessage lastMessage = conversation.getLastMessage(); txt_content.setText( SmileUtils.getSmiledText(context, getMessageDigest(lastMessage, context)), BufferType.SPANNABLE); txt_time.setText(DateUtils.getTimestampString(new Date(lastMessage.getMsgTime()))); if (lastMessage.status == EMMessage.Status.SUCCESS) { txt_state.setText("送达"); // txt_state.setBackgroundResource(R.drawable.btn_bg_orgen); } else if (lastMessage.status == EMMessage.Status.FAIL) { txt_state.setText("失败"); // txt_state.setBackgroundResource(R.drawable.btn_bg_red); } else if (lastMessage.direct == EMMessage.Direct.RECEIVE) { txt_state.setText("已读"); txt_state.setBackgroundResource(R.drawable.btn_bg_blue); } } txt_del.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { deleteID = position; Tipdialog = new WarnTipDialog((Activity) context, "您确定要删除该聊天吗?"); Tipdialog.setBtnOkLinstener(onclick); Tipdialog.show(); } }); } return convertView; }