/** * 根据消息内容和消息类型获取消息内容提示 * * @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; }
@Override public void logout(final EMCallBack callback) { endCall(); super.logout( new EMCallBack() { @Override public void onSuccess() { // TODO Auto-generated method stub setContactList(null); setRobotList(null); getModel().closeDB(); if (callback != null) { callback.onSuccess(); } } @Override public void onError(int code, String message) { // TODO Auto-generated method stub } @Override public void onProgress(int progress, String status) { // TODO Auto-generated method stub if (callback != null) { callback.onProgress(progress, status); } } }); }
private void addContentToChat(final String toChatName) { // TODO Auto-generated method stub final Intent intent = new Intent(this, ChatActivity.class); intent.putExtra("userId", toChatName); if (MyApplication.getInstance().getUserName().equals(toChatName)) { startActivity(new Intent(this, AlertDialog.class).putExtra("msg", "天了噜~怎么可以添加自己为好友呢?")); return; } if (!((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList().containsKey(toChatName)) { // 如果不在好友列表,先加好友 new Thread( new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { EMContactManager.getInstance().addContact(toChatName, ""); Log.i(TAG, "添加" + toChatName + "成功"); startActivity(intent); } catch (EaseMobException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }) .start(); } else { Log.i(TAG, "对方已在好友已经在好友列表中,直接聊天"); startActivity(intent); } }
/** 设置当前用户昵称 */ public static void setCurrentUserNick(TextView textView) { User user = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getUserProfileManager().getCurrentUserInfo(); if (textView != null) { textView.setText(user.getNick()); } }
@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; } }
public void asyncFetchUserInfo(String username) { ((DemoHXSDKHelper) HXSDKHelper.getInstance()) .getUserProfileManager() .asyncGetUserInfo( username, new EMValueCallBack<User>() { @Override public void onSuccess(User user) { if (user != null) { tvNickName.setText(user.getNick()); if (!TextUtils.isEmpty(user.getAvatar())) { Glide.with(UserProfileActivity.this) .load(user.getAvatar()) .placeholder(R.mipmap.default_avatar) .into(headAvatar); } else { Glide.with(UserProfileActivity.this) .load(R.mipmap.default_avatar) .into(headAvatar); } UserUtils.saveUserInfo(user); } } @Override public void onError(int error, String errorMsg) {} }); }
@Override protected void initHXOptions() { super.initHXOptions(); // you can also get EMChatOptions to set related SDK options EMChatOptions options = EMChatManager.getInstance().getChatOptions(); options.allowChatroomOwnerLeave(getModel().isChatroomOwnerLeaveAllowed()); }
@Override protected void onDestroy() { if (syncListener != null) { HXSDKHelper.getInstance().removeSyncGroupListener(syncListener); syncListener = null; } super.onDestroy(); instance = null; }
@Override public void onDestroy() { if (contactSyncListener != null) { HXSDKHelper.getInstance().removeSyncContactListener(contactSyncListener); contactSyncListener = null; } if (blackListSyncListener != null) { HXSDKHelper.getInstance().removeSyncBlackListListener(blackListSyncListener); } if (contactInfoSyncListener != null) { ((DemoHXSDKHelper) HXSDKHelper.getInstance()) .getUserProfileManager() .removeSyncContactInfoListener(contactInfoSyncListener); } super.onDestroy(); }
/** * 根据username获取相应user,由于demo没有真实的用户数据,这里给的模拟的数据; * * @param username * @return */ public static User getUserInfo(String username) { User user = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList().get(username); if (user == null) { user = new User(username); } if (user != null) { // demo没有这些数据,临时填充 if (TextUtils.isEmpty(user.getNick())) user.setNick(username); } return user; }
/** 设置当前用户头像 */ public static void setCurrentUserAvatar(Context context, ImageView imageView) { User user = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getUserProfileManager().getCurrentUserInfo(); if (user != null && user.getAvatar() != null) { Picasso.with(context) .load(user.getAvatar()) .placeholder(R.drawable.default_avatar) .into(imageView); } else { Picasso.with(context).load(R.drawable.default_avatar).into(imageView); } }
@Override protected void onDestroy() { super.onDestroy(); HXSDKHelper.getInstance().isVideoCalling = false; stopMonitor(); try { callHelper.setSurfaceView(null); cameraHelper.stopCapture(); oppositeSurface = null; cameraHelper = null; } catch (Exception e) { } }
@Override protected void initListener() { super.initListener(); IntentFilter callFilter = new IntentFilter(EMChatManager.getInstance().getIncomingCallBroadcastAction()); if (callReceiver == null) { callReceiver = new CallReceiver(); } // 娉ㄥ唽閫氳瘽骞挎挱鎺ユ敹鑰� appContext.registerReceiver(callReceiver, callFilter); // 娉ㄥ唽娑堟伅浜嬩欢鐩戝惉 initEventListener(); }
/** 获取联系人列表,并过滤掉黑名单和排序 */ private void getContactList() { contactList.clear(); // 获取本地好友列表 Map<String, User> users = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList(); // 报空指针错误 (henry for revise) if (users == null) { return; } Iterator<Entry<String, User>> iterator = users.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, User> entry = iterator.next(); if (!entry.getKey().equals(Constant.NEW_FRIENDS_USERNAME) && !entry.getKey().equals(Constant.GROUP_USERNAME) && !entry.getKey().equals(Constant.CHAT_ROOM) && !entry.getKey().equals(Constant.CHAT_ROBOT) && !blackList.contains(entry.getKey())) contactList.add(entry.getValue()); } // 排序 Collections.sort( contactList, new Comparator<User>() { @Override public int compare(User lhs, User rhs) { return lhs.getUsername().compareTo(rhs.getUsername()); } }); // // if(users.get(Constant.CHAT_ROBOT)!=null){ // contactList.add(0, users.get(Constant.CHAT_ROBOT)); // } // // 加入"群聊"和"聊天室" // if(users.get(Constant.CHAT_ROOM) != null) // contactList.add(0, users.get(Constant.CHAT_ROOM)); // if(users.get(Constant.GROUP_USERNAME) != null) // contactList.add(0, users.get(Constant.GROUP_USERNAME)); // 把"申请与通知"添加到首位 if (users.get(Constant.NEW_FRIENDS_USERNAME) != null) contactList.add(0, users.get(Constant.NEW_FRIENDS_USERNAME)); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { finish(); return; } setContentView(R.layout.activity_voice_call); HXSDKHelper.getInstance().isVoiceCalling = true; comingBtnContainer = (LinearLayout) findViewById(R.id.ll_coming_call); refuseBtn = (Button) findViewById(R.id.btn_refuse_call); answerBtn = (Button) findViewById(R.id.btn_answer_call); hangupBtn = (Button) findViewById(R.id.btn_hangup_call); muteImage = (ImageView) findViewById(R.id.iv_mute); handsFreeImage = (ImageView) findViewById(R.id.iv_handsfree); userImage = (ImageView) findViewById(R.id.swing_card); callStateTextView = (TextView) findViewById(R.id.tv_call_state); nickTextView = (TextView) findViewById(R.id.tv_nick); durationTextView = (TextView) findViewById(R.id.tv_calling_duration); chronometer = (Chronometer) findViewById(R.id.chronometer); voiceContronlLayout = (LinearLayout) findViewById(R.id.ll_voice_control); refuseBtn.setOnClickListener(this); answerBtn.setOnClickListener(this); hangupBtn.setOnClickListener(this); muteImage.setOnClickListener(this); handsFreeImage.setOnClickListener(this); getWindow() .addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); // 注册语音电话的状态的监听 addCallStateListener(); msgid = UUID.randomUUID().toString(); username = getIntent().getStringExtra("username"); // 语音电话是否为接收的 isInComingCall = getIntent().getBooleanExtra("isComingCall", false); // 设置通话人头像 UserUtils.setUserAvatar(this, username, userImage); // 设置通话人 /** 根据usename匹配本地好友获得昵称 */ FriendDao friendDao = new FriendDao(this); Friend friend = friendDao.getFriend(username); nickTextView.setText(friend.getTitle()); if (!isInComingCall) { // 拨打电话 soundPool = new SoundPool(1, AudioManager.STREAM_RING, 0); outgoing = soundPool.load(this, R.raw.outgoing, 1); comingBtnContainer.setVisibility(View.INVISIBLE); hangupBtn.setVisibility(View.VISIBLE); st1 = getResources().getString(R.string.Are_connected_to_each_other); callStateTextView.setText(st1); handler.postDelayed( new Runnable() { public void run() { streamID = playMakeCallSounds(); } }, 300); try { // 拨打语音电话 EMChatManager.getInstance().makeVoiceCall(username); } catch (EMServiceNotReadyException e) { e.printStackTrace(); final String st2 = getResources().getString(R.string.Is_not_yet_connected_to_the_server); runOnUiThread( new Runnable() { public void run() { Toast.makeText(VoiceCallActivity.this, st2, Toast.LENGTH_SHORT).show(); } }); } } else { // 有电话进来 voiceContronlLayout.setVisibility(View.INVISIBLE); Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); audioManager.setMode(AudioManager.MODE_RINGTONE); audioManager.setSpeakerphoneOn(true); ringtone = RingtoneManager.getRingtone(this, ringUri); ringtone.play(); } }
@Override protected void onDestroy() { super.onDestroy(); HXSDKHelper.getInstance().isVoiceCalling = false; }
@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; }
/** * 保存或更新某个用户 * * @param user */ public static void saveUserInfo(User newUser) { if (newUser == null || newUser.getUsername() == null) { return; } ((DemoHXSDKHelper) HXSDKHelper.getInstance()).saveContact(newUser); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { finish(); return; } setContentView(R.layout.activity_video_call); HXSDKHelper.getInstance().isVideoCalling = true; getWindow() .addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); callStateTextView = (TextView) findViewById(R.id.tv_call_state); comingBtnContainer = (LinearLayout) findViewById(R.id.ll_coming_call); rootContainer = (RelativeLayout) findViewById(R.id.root_layout); refuseBtn = (Button) findViewById(R.id.btn_refuse_call); answerBtn = (Button) findViewById(R.id.btn_answer_call); hangupBtn = (Button) findViewById(R.id.btn_hangup_call); muteImage = (ImageView) findViewById(R.id.iv_mute); handsFreeImage = (ImageView) findViewById(R.id.iv_handsfree); callStateTextView = (TextView) findViewById(R.id.tv_call_state); nickTextView = (TextView) findViewById(R.id.tv_nick); chronometer = (Chronometer) findViewById(R.id.chronometer); voiceContronlLayout = (LinearLayout) findViewById(R.id.ll_voice_control); btnsContainer = (RelativeLayout) findViewById(R.id.ll_btns); topContainer = (LinearLayout) findViewById(R.id.ll_top_container); bottomContainer = (LinearLayout) findViewById(R.id.ll_bottom_container); monitorTextView = (TextView) findViewById(R.id.tv_call_monitor); refuseBtn.setOnClickListener(this); answerBtn.setOnClickListener(this); hangupBtn.setOnClickListener(this); muteImage.setOnClickListener(this); handsFreeImage.setOnClickListener(this); rootContainer.setOnClickListener(this); msgid = UUID.randomUUID().toString(); // 获取通话是否为接收方向的 isInComingCall = getIntent().getBooleanExtra("isComingCall", false); username = getIntent().getStringExtra("username"); // 设置通话人 nickTextView.setText(username); // 显示本地图像的surfaceview localSurface = (SurfaceView) findViewById(R.id.local_surface); localSurface.setZOrderMediaOverlay(true); localSurface.setZOrderOnTop(true); localSurfaceHolder = localSurface.getHolder(); // 获取callHelper,cameraHelper callHelper = EMVideoCallHelper.getInstance(); cameraHelper = new CameraHelper(callHelper, localSurfaceHolder); // 显示对方图像的surfaceview oppositeSurface = (SurfaceView) findViewById(R.id.opposite_surface); oppositeSurfaceHolder = oppositeSurface.getHolder(); // 设置显示对方图像的surfaceview callHelper.setSurfaceView(oppositeSurface); localSurfaceHolder.addCallback(new LocalCallback()); oppositeSurfaceHolder.addCallback(new OppositeCallback()); // 设置通话监听 addCallStateListener(); if (!isInComingCall) { // 拨打电话 soundPool = new SoundPool(1, AudioManager.STREAM_RING, 0); outgoing = soundPool.load(this, R.raw.outgoing, 1); comingBtnContainer.setVisibility(View.INVISIBLE); hangupBtn.setVisibility(View.VISIBLE); String st = getResources().getString(R.string.Are_connected_to_each_other); callStateTextView.setText(st); handler.postDelayed( new Runnable() { public void run() { streamID = playMakeCallSounds(); } }, 300); } else { // 有电话进来 voiceContronlLayout.setVisibility(View.INVISIBLE); localSurface.setVisibility(View.INVISIBLE); Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); audioManager.setMode(AudioManager.MODE_RINGTONE); audioManager.setSpeakerphoneOn(true); ringtone = RingtoneManager.getRingtone(this, ringUri); ringtone.play(); } }
/** 手机震动和声音提示 */ public void viberateAndPlayTone(EMMessage message) { if (message != null) { if (EMChatManager.getInstance().isSlientMessage(message)) { return; } } com.easemob.applib.model.HXSDKModel model = HXSDKHelper.getInstance().getModel(); if (!model.getSettingMsgNotification()) { return; } if (System.currentTimeMillis() - lastNotifiyTime < 1000) { // received new messages within 2 seconds, skip play ringtone return; } try { lastNotifiyTime = System.currentTimeMillis(); // 判断是否处于静音模式 if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) { EMLog.e(TAG, "in slient mode now"); return; } if (model.getSettingMsgVibrate()) { long[] pattern = new long[] {0, 180, 80, 120}; vibrator.vibrate(pattern, -1); } if (model.getSettingMsgSound()) { if (ringtone == null) { Uri notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); ringtone = RingtoneManager.getRingtone(appContext, notificationUri); if (ringtone == null) { EMLog.d(TAG, "cant find ringtone at:" + notificationUri.getPath()); return; } } if (!ringtone.isPlaying()) { String vendor = Build.MANUFACTURER; ringtone.play(); // for samsung S3, we meet a bug that the phone will // continue ringtone without stop // so add below special handler to stop it after 3s if // needed if (vendor != null && vendor.toLowerCase().contains("samsung")) { Thread ctlThread = new Thread() { public void run() { try { Thread.sleep(3000); if (ringtone.isPlaying()) { ringtone.stop(); } } catch (Exception e) { } } }; ctlThread.run(); } } } } catch (Exception e) { e.printStackTrace(); } }
@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // 防止被T后,没点确定按钮然后按了home键,长期在后台又进app导致的crash if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) return; inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); listView = (ListView) getView().findViewById(R.id.list); sidebar = (Sidebar) getView().findViewById(R.id.sidebar); sidebar.setListView(listView); // 黑名单列表 blackList = EMContactManager.getInstance().getBlackListUsernames(); contactList = new ArrayList<User>(); // 获取设置contactlist getContactList(); // 搜索框 query = (EditText) getView().findViewById(R.id.query); query.setHint(R.string.search); clearSearch = (ImageButton) getView().findViewById(R.id.search_clear); query.addTextChangedListener( new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { adapter.getFilter().filter(s); if (s.length() > 0) { clearSearch.setVisibility(View.VISIBLE); } else { clearSearch.setVisibility(View.INVISIBLE); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void afterTextChanged(Editable s) {} }); clearSearch.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { query.getText().clear(); hideSoftKeyboard(); } }); // 设置adapter adapter = new ContactAdapter(getActivity(), R.layout.easeui_row_contact, contactList); listView.setAdapter(adapter); listView.setOnItemClickListener( new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String username = adapter.getItem(position).getUsername(); if (Constant.NEW_FRIENDS_USERNAME.equals(username)) { // 进入申请与通知页面 User user = ((DemoHXSDKHelper) HXSDKHelper.getInstance()) .getContactList() .get(Constant.NEW_FRIENDS_USERNAME); user.setUnreadMsgCount(0); startActivity(new Intent(getActivity(), NewFriendsMsgActivity.class)); } else if (Constant.GROUP_USERNAME.equals(username)) { // 进入群聊列表页面 startActivity(new Intent(getActivity(), GroupsActivity.class)); } else if (Constant.CHAT_ROOM.equals(username)) { // 进入聊天室列表页面 startActivity(new Intent(getActivity(), PublicChatRoomsActivity.class)); } else if (Constant.CHAT_ROBOT.equals(username)) { // 进入Robot列表页面 startActivity(new Intent(getActivity(), RobotsActivity.class)); } else { // demo中直接进入聊天页面,实际一般是进入用户详情页 startActivity( new Intent(getActivity(), ChatActivity.class) .putExtra("userId", adapter.getItem(position).getUsername())); } } }); listView.setOnTouchListener( new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // 隐藏软键盘 if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) { if (getActivity().getCurrentFocus() != null) inputMethodManager.hideSoftInputFromWindow( getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } return false; } }); ImageView addContactView = (ImageView) getView().findViewById(R.id.iv_new_contact); // 进入添加好友页 addContactView.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getActivity(), AddContactActivity.class)); } }); registerForContextMenu(listView); progressBar = (View) getView().findViewById(R.id.progress_bar); contactSyncListener = new HXContactSyncListener(); HXSDKHelper.getInstance().addSyncContactListener(contactSyncListener); blackListSyncListener = new HXBlackListSyncListener(); HXSDKHelper.getInstance().addSyncBlackListListener(blackListSyncListener); contactInfoSyncListener = new HXContactInfoSyncListener(); ((DemoHXSDKHelper) HXSDKHelper.getInstance()) .getUserProfileManager() .addSyncContactInfoListener(contactInfoSyncListener); if (!HXSDKHelper.getInstance().isContactsSyncedWithServer()) { progressBar.setVisibility(View.VISIBLE); } else { progressBar.setVisibility(View.GONE); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.easeui_fragment_groups); instance = this; inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); grouplist = EMGroupManager.getInstance().getAllGroups(); groupListView = (ListView) findViewById(R.id.list); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.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 OnRefreshListener() { @Override public void onRefresh() { MainActivity.asyncFetchGroupsFromServer(); } }); groupAdapter = new GroupAdapter(this, 1, grouplist); groupListView.setAdapter(groupAdapter); groupListView.setOnItemClickListener( new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position == 1) { // 新建群聊 startActivityForResult(new Intent(GroupsActivity.this, NewGroupActivity.class), 0); } else if (position == 2) { // 添加公开群 startActivityForResult( new Intent(GroupsActivity.this, PublicGroupsActivity.class), 0); } else { // 进入群聊 Intent intent = new Intent(GroupsActivity.this, ChatActivity.class); // it is group chat intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP); intent.putExtra("groupId", groupAdapter.getItem(position - 3).getGroupId()); startActivityForResult(intent, 0); } } }); groupListView.setOnTouchListener( new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) { if (getCurrentFocus() != null) inputMethodManager.hideSoftInputFromWindow( getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } return false; } }); progressBar = (View) findViewById(R.id.progress_bar); syncListener = new SyncListener(); HXSDKHelper.getInstance().addSyncGroupListener(syncListener); if (!HXSDKHelper.getInstance().isGroupsSyncedWithServer()) { progressBar.setVisibility(View.VISIBLE); } else { progressBar.setVisibility(View.GONE); } refresh(); }
@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); errorText = (TextView) errorItem.findViewById(R.id.tv_connect_errormsg); // contact list contactList = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList(); listView = (ListView) getView().findViewById(R.id.list); adapter = new ChatHistoryAdapter(getActivity(), 1, loadUsersWithRecentChat()); // 设置adapter listView.setAdapter(adapter); final String st = getResources().getString(R.string.Cant_chat_with_yourself); listView.setOnItemClickListener( new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { EMContact emContact = adapter.getItem(position); if (adapter .getItem(position) .getUsername() .equals(DiDiApplication.getInstance().getUserName())) Toast.makeText(getActivity(), st, 0).show(); else { // 进入聊天页面 Intent intent = new Intent(getActivity(), ChatActivity.class); if (emContact instanceof EMGroup) { // it is group chat intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP); intent.putExtra("groupId", ((EMGroup) emContact).getGroupId()); } else { // it is single chat intent.putExtra("userId", emContact.getUsername()); } startActivity(intent); } } }); // 注册上下文菜单 registerForContextMenu(listView); listView.setOnTouchListener( new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // 隐藏软键盘 if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) { if (getActivity().getCurrentFocus() != null) inputMethodManager.hideSoftInputFromWindow( getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } return false; } }); // 搜索框 query = (EditText) getView().findViewById(R.id.query); // 搜索框中清除button clearSearch = (ImageButton) getView().findViewById(R.id.search_clear); query.addTextChangedListener( new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { adapter.getFilter().filter(s); if (s.length() > 0) { clearSearch.setVisibility(View.VISIBLE); } else { clearSearch.setVisibility(View.INVISIBLE); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void afterTextChanged(Editable s) {} }); clearSearch.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { query.getText().clear(); } }); }
public void playVoice(String filePath) { if (!(new File(filePath).exists())) { return; } ((ChatActivity) activity).playMsgId = message.getMsgId(); AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE); mediaPlayer = new MediaPlayer(); if (HXSDKHelper.getInstance().getModel().getSettingMsgSpeaker()) { 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; mediaPlayer.start(); showAnimation(); // 如果是接收的消息 if (message.direct == EMMessage.Direct.RECEIVE) { try { if (!message.isAcked) { message.isAcked = true; // 告知对方已读这条消息 if (chatType != ChatType.GroupChat && chatType != ChatType.ChatRoom) EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId()); } } catch (Exception e) { message.isAcked = false; } if (!message.isListened() && iv_read_status != null && iv_read_status.getVisibility() == View.VISIBLE) { // 隐藏自己未播放这条语音消息的标志 iv_read_status.setVisibility(View.INVISIBLE); EMChatManager.getInstance().setMessageListened(message); } } } catch (Exception e) { } }