/**
   * 转发消息
   *
   * @param forward_msg_id
   */
  protected void forwardMessage(String forward_msg_id) {
    final EMMessage forward_msg = EMClient.getInstance().chatManager().getMessage(forward_msg_id);
    EMMessage.Type type = forward_msg.getType();
    switch (type) {
      case TXT:
        if (forward_msg.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_BIG_EXPRESSION, false)) {
          sendBigExpressionMessage(
              ((EMTextMessageBody) forward_msg.getBody()).getMessage(),
              forward_msg.getStringAttribute(EaseConstant.MESSAGE_ATTR_EXPRESSION_ID, null));
        } else {
          // 获取消息内容,发送消息
          String content = ((EMTextMessageBody) forward_msg.getBody()).getMessage();
          sendTextMessage(content);
        }
        break;
      case IMAGE:
        // 发送图片
        String filePath = ((EMImageMessageBody) forward_msg.getBody()).getLocalUrl();
        if (filePath != null) {
          File file = new File(filePath);
          if (!file.exists()) {
            // 不存在大图发送缩略图
            filePath = ((EMImageMessageBody) forward_msg.getBody()).thumbnailLocalPath();
          }
          sendImageMessage(filePath);
        }
        break;
      default:
        break;
    }

    if (forward_msg.getChatType() == EMMessage.ChatType.ChatRoom) {
      EMClient.getInstance().chatroomManager().leaveChatRoom(forward_msg.getTo());
    }
  }
Пример #2
0
  public void init() {
    if (EaseUI.getInstance().init(mAppContext, null)) {
      easeUI = EaseUI.getInstance();

      setEmojiProvider();
      EMConnectionListener connectionListener =
          new EMConnectionListener() {
            @Override
            public void onConnected() {}

            @Override
            public void onDisconnected(int i) {
              if (i == EMError.USER_REMOVED) {
                onCurrentAccountRemoved();
              } else if (i == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                onConnectionConflict();
              }
            }
          };
      // 注册连接监听
      EMClient.getInstance().addConnectionListener(connectionListener);
      CallReceiver callReceiver = null;
      IntentFilter callFilter =
          new IntentFilter(EMClient.getInstance().callManager().getIncomingCallBroadcastAction());
      if (callReceiver == null) {
        callReceiver = new CallReceiver();
      }

      // 注册通话广播接收者
      mAppContext.registerReceiver(callReceiver, callFilter);
      registerEventListener();
    }
  }
  /** 设置属性,监听等 */
  protected void setUpView() {
    titleBar.setTitle(toChatUsername);
    if (chatType == EaseConstant.CHATTYPE_SINGLE) { // 单聊
      // 设置标题
      if (EaseUserUtils.getUserInfo(toChatUsername) != null) {
        titleBar.setTitle(EaseUserUtils.getUserInfo(toChatUsername).getNick());
      }
      titleBar.setRightImageResource(R.drawable.ease_mm_title_remove);
    } else {
      titleBar.setRightImageResource(R.drawable.ease_to_group_details_normal);
      if (chatType == EaseConstant.CHATTYPE_GROUP) {
        // 群聊
        EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
        if (group != null) titleBar.setTitle(group.getGroupName());
        // 监听当前会话的群聊解散被T事件
        groupListener = new GroupListener();
        EMClient.getInstance().groupManager().addGroupChangeListener(groupListener);
      } else {
        onChatRoomViewCreation();
      }
    }
    if (chatType != EaseConstant.CHATTYPE_CHATROOM) {
      onConversationInit();
      onMessageListInit();
    }

    // 设置标题栏点击事件
    titleBar.setLeftLayoutClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            getActivity().finish();
          }
        });
    titleBar.setRightLayoutClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            if (chatType == EaseConstant.CHATTYPE_SINGLE) {
              emptyHistory();
            } else {
              toGroupDetails();
            }
          }
        });

    setRefreshLayoutListener();

    // show forward message if the message is not null
    String forward_msg_id = getArguments().getString("forward_msg_id");
    if (forward_msg_id != null) {
      // 发送要转发的消息
      forwardMessage(forward_msg_id);
    }
  }
Пример #4
0
  @Override
  public void onClick(View v) {
    int i = v.getId();
    if (i == R.id.btn_refuse_call) {
      refuseBtn.setEnabled(false);
      handler.sendEmptyMessage(MSG_CALL_REJECT);

    } else if (i == R.id.btn_answer_call) {
      answerBtn.setEnabled(false);
      closeSpeakerOn();
      callStateTextView.setText("正在接听...");
      comingBtnContainer.setVisibility(View.INVISIBLE);
      hangupBtn.setVisibility(View.VISIBLE);
      voiceContronlLayout.setVisibility(View.VISIBLE);
      handler.sendEmptyMessage(MSG_CALL_ANSWER);

    } else if (i == R.id.btn_hangup_call) {
      hangupBtn.setEnabled(false);
      chronometer.stop();
      endCallTriggerByMe = true;
      callStateTextView.setText(getResources().getString(R.string.hanging_up));
      handler.sendEmptyMessage(MSG_CALL_END);

    } else if (i == R.id.iv_mute) {
      if (isMuteState) {
        // 关闭静音
        muteImage.setImageResource(R.drawable.em_icon_mute_normal);
        EMClient.getInstance().callManager().resumeVoiceTransfer();
        isMuteState = false;
      } else {
        // 打开静音
        muteImage.setImageResource(R.drawable.em_icon_mute_on);
        EMClient.getInstance().callManager().pauseVoiceTransfer();
        isMuteState = true;
      }

    } else if (i == R.id.iv_handsfree) {
      if (isHandsfreeState) {
        // 关闭免提
        handsFreeImage.setImageResource(R.drawable.em_icon_speaker_normal);
        closeSpeakerOn();
        isHandsfreeState = false;
      } else {
        handsFreeImage.setImageResource(R.drawable.em_icon_speaker_on);
        openSpeakerOn();
        isHandsfreeState = true;
      }

    } else {
    }
  }
  @Override
  public void onDestroy() {
    super.onDestroy();
    if (groupListener != null) {
      EMClient.getInstance().groupManager().removeGroupChangeListener(groupListener);
    }
    if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
      EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
    }

    if (chatRoomChangeListener != null) {
      EMClient.getInstance().chatroomManager().removeChatRoomChangeListener(chatRoomChangeListener);
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ease_activity_show_file);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    final EMFileMessageBody messageBody = getIntent().getParcelableExtra("msgbody");
    file = new File(messageBody.getLocalUrl());
    // set head map
    final Map<String, String> maps = new HashMap<String, String>();
    if (!TextUtils.isEmpty(messageBody.getSecret())) {
      maps.put("share-secret", messageBody.getSecret());
    }

    // download file
    EMClient.getInstance()
        .chatManager()
        .downloadFile(
            messageBody.getRemoteUrl(),
            messageBody.getLocalUrl(),
            maps,
            new EMCallBack() {

              @Override
              public void onSuccess() {
                runOnUiThread(
                    new Runnable() {
                      public void run() {
                        FileUtils.openFile(file, EaseShowNormalFileActivity.this);
                        finish();
                      }
                    });
              }

              @Override
              public void onProgress(final int progress, String status) {
                runOnUiThread(
                    new Runnable() {
                      public void run() {
                        progressBar.setProgress(progress);
                      }
                    });
              }

              @Override
              public void onError(int error, final String msg) {
                runOnUiThread(
                    new Runnable() {
                      public void run() {
                        if (file != null && file.exists() && file.isFile()) file.delete();
                        String str4 = getResources().getString(R.string.Failed_to_download_file);
                        Toast.makeText(
                                EaseShowNormalFileActivity.this, str4 + msg, Toast.LENGTH_SHORT)
                            .show();
                        finish();
                      }
                    });
              }
            });
  }
 @Override
 public void onResume() {
   super.onResume();
   if (isMessageListInited) messageList.refresh();
   EaseUI.getInstance().pushActivity(getActivity());
   // register the event listener when enter the foreground
   EMClient.getInstance().chatManager().addMessageListener(msgListener);
 }
 public void onBackPressed() {
   if (inputMenu.onBackPressed()) {
     getActivity().finish();
     if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
       EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
     }
   }
 }
  @Override
  public void onStop() {
    super.onStop();
    // unregister this event listener when this activity enters the
    // background
    EMClient.getInstance().chatManager().removeMessageListener(msgListener);

    // 把此activity 从foreground activity 列表里移除
    EaseUI.getInstance().popActivity(getActivity());
  }
Пример #10
0
 @Override
 protected void onResume() {
   super.onResume();
   if (!EMClient.getInstance().isLoggedInBefore()) {
     // 跳转到登录界面
     Intent intent = new Intent(this, MLSignInActivity.class);
     superJump(intent);
     this.finish();
   }
 }
Пример #11
0
 /**
  * send @ message, only support group chat message
  *
  * @param content
  */
 private void sendAtMessage(String content) {
   if (chatType != EaseConstant.CHATTYPE_GROUP) {
     EMLog.e(TAG, "only support group chat message");
     return;
   }
   EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
   EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
   if (EMClient.getInstance().getCurrentUser().equals(group.getOwner())
       && EaseAtMessageHelper.get().containsAtAll(content)) {
     message.setAttribute(
         EaseConstant.MESSAGE_ATTR_AT_MSG, EaseConstant.MESSAGE_ATTR_VALUE_AT_MSG_ALL);
   } else {
     message.setAttribute(
         EaseConstant.MESSAGE_ATTR_AT_MSG,
         EaseAtMessageHelper.get()
             .atListToJsonArray(EaseAtMessageHelper.get().getAtMessageUsernames(content)));
   }
   sendMessage(message);
 }
 public BaseLazyChatMessageAdapter(
     Context cxt,
     String username,
     EMConversation.EMConversationType type,
     int firstLoadDataCount) {
   this.mContext = cxt;
   this.mUserName = username;
   this.mConversation = EMClient.getInstance().chatManager().getConversation(username, type, true);
   // 首次加载
   mConversation.loadMoreMsgFromDB("", firstLoadDataCount);
 }
Пример #13
0
 public void onBackPressed() {
   if (inputMenu.onBackPressed()) {
     getActivity().finish();
     if (chatType == EaseConstant.CHATTYPE_GROUP) {
       EaseAtMessageHelper.get().removeAtMeGroup(toChatUsername);
       EaseAtMessageHelper.get().cleanToAtUserList();
     }
     if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
       EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
     }
   }
 }
Пример #14
0
  @Override
  public void onResume() {
    super.onResume();
    if (isMessageListInited) messageList.refresh();
    EaseUI.getInstance().pushActivity(getActivity());
    // register the event listener when enter the foreground
    EMClient.getInstance().chatManager().addMessageListener(this);

    if (chatType == EaseConstant.CHATTYPE_GROUP) {
      EaseAtMessageHelper.get().removeAtMeGroup(toChatUsername);
    }
  }
Пример #15
0
 /**
  * input @
  *
  * @param username
  */
 protected void inputAtUsername(String username, boolean autoAddAtSymbol) {
   if (EMClient.getInstance().getCurrentUser().equals(username)
       || chatType != EaseConstant.CHATTYPE_GROUP) {
     return;
   }
   EaseAtMessageHelper.get().addAtUser(username);
   if (EaseUserUtils.getUserInfo(username) != null) {
     username = EaseUserUtils.getUserInfo(username).getNick();
   }
   if (autoAddAtSymbol) inputMenu.insertText("@" + username + " ");
   else inputMenu.insertText(username + " ");
 }
Пример #16
0
  protected void addChatRoomChangeListenr() {
    chatRoomChangeListener =
        new EMChatRoomChangeListener() {

          @Override
          public void onChatRoomDestroyed(String roomId, String roomName) {
            if (roomId.equals(toChatUsername)) {
              showChatroomToast(
                  " room : " + roomId + " with room name : " + roomName + " was destroyed");
              getActivity().finish();
            }
          }

          @Override
          public void onMemberJoined(String roomId, String participant) {
            showChatroomToast("member : " + participant + " join the room : " + roomId);
          }

          @Override
          public void onMemberExited(String roomId, String roomName, String participant) {
            showChatroomToast(
                "member : "
                    + participant
                    + " leave the room : "
                    + roomId
                    + " room name : "
                    + roomName);
          }

          @Override
          public void onMemberKicked(String roomId, String roomName, String participant) {
            if (roomId.equals(toChatUsername)) {
              String curUser = EMClient.getInstance().getCurrentUser();
              if (curUser.equals(participant)) {
                EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
                getActivity().finish();
              } else {
                showChatroomToast(
                    "member : "
                        + participant
                        + " was kicked from the room : "
                        + roomId
                        + " room name : "
                        + roomName);
              }
            }
          }
        };

    EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomChangeListener);
  }
Пример #17
0
  protected void onChatRoomViewCreation() {
    final ProgressDialog pd = ProgressDialog.show(getActivity(), "", "Joining......");
    EMClient.getInstance()
        .chatroomManager()
        .joinChatRoom(
            toChatUsername,
            new EMValueCallBack<EMChatRoom>() {

              @Override
              public void onSuccess(final EMChatRoom value) {
                getActivity()
                    .runOnUiThread(
                        new Runnable() {
                          @Override
                          public void run() {
                            if (getActivity().isFinishing()
                                || !toChatUsername.equals(value.getId())) return;
                            pd.dismiss();
                            EMChatRoom room =
                                EMClient.getInstance()
                                    .chatroomManager()
                                    .getChatRoom(toChatUsername);
                            if (room != null) {
                              titleBar.setTitle(room.getName());
                            } else {
                              titleBar.setTitle(toChatUsername);
                            }
                            EMLog.d(TAG, "join room success : " + room.getName());
                            addChatRoomChangeListenr();
                            onConversationInit();
                            onMessageListInit();
                          }
                        });
              }

              @Override
              public void onError(final int error, String errorMsg) {
                // TODO Auto-generated method stub
                EMLog.d(TAG, "join room failure : " + error);
                getActivity()
                    .runOnUiThread(
                        new Runnable() {
                          @Override
                          public void run() {
                            pd.dismiss();
                          }
                        });
                getActivity().finish();
              }
            });
  }
Пример #18
0
    @Override
    protected FilterResults performFiltering(CharSequence prefix) {
      FilterResults results = new FilterResults();

      if (mOriginalValues == null) {
        mOriginalValues = new ArrayList<EMConversation>();
      }
      if (prefix == null || prefix.length() == 0) {
        results.values = copyConversationList;
        results.count = copyConversationList.size();
      } else {
        String prefixString = prefix.toString();
        final int count = mOriginalValues.size();
        final ArrayList<EMConversation> newValues = new ArrayList<EMConversation>();

        for (int i = 0; i < count; i++) {
          final EMConversation value = mOriginalValues.get(i);
          String username = value.getUserName();

          EMGroup group = EMClient.getInstance().groupManager().getGroup(username);
          if (group != null) {
            username = group.getGroupName();
          } else {
            EaseUser user = EaseUserUtils.getUserInfo(username);
            // TODO: not support Nick anymore
            //                        if(user != null && user.getNick() != null)
            //                            username = user.getNick();
          }

          // First match against the whole ,non-splitted value
          if (username.startsWith(prefixString)) {
            newValues.add(value);
          } else {
            final String[] words = username.split(" ");
            final int wordCount = words.length;

            // Start at index 0, in case valueText starts with space(s)
            for (int k = 0; k < wordCount; k++) {
              if (words[k].startsWith(prefixString)) {
                newValues.add(value);
                break;
              }
            }
          }
        }

        results.values = newValues;
        results.count = newValues.size();
      }
      return results;
    }
Пример #19
0
  /** 界面初始化操作 */
  private void init() {
    mActivity = this;

    if (EMClient.getInstance().isConnected()) {
      mConnectionFabBtn.setImageResource(R.mipmap.ic_signal_wifi_on_white_24dp);
      mConnectionFabBtn.setVisibility(View.GONE);
    } else {
      mConnectionFabBtn.setImageResource(R.mipmap.ic_signal_wifi_off_white_24dp);
      mConnectionFabBtn.setVisibility(View.VISIBLE);
    }

    setSupportActionBar(getToolbar());
    getSupportActionBar().setTitle(R.string.ml_chat);
  }
Пример #20
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // 判断当前是否已经登录
    if (EMClient.getInstance().isLoggedInBefore()) {
      // 加载群组到内存
      EMClient.getInstance().groupManager().loadAllGroups();
      // 加载所有本地会话到内存
      EMClient.getInstance().chatManager().loadAllConversations();
    } else {
      // 跳转到登录界面
      Intent intent = new Intent(this, MLSignInActivity.class);
      superJump(intent);
      this.finish();
    }
    // 将主题设置为正常主题
    setTheme(R.style.MLTheme_Default);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ButterKnife.bind(this);

    init();
    initView();
  }
Пример #21
0
 /** 点击进入群组详情 */
 protected void toGroupDetails() {
   if (chatType == EaseConstant.CHATTYPE_GROUP) {
     EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
     if (group == null) {
       Toast.makeText(getActivity(), R.string.gorup_not_found, 0).show();
       return;
     }
     if (chatFragmentListener != null) {
       chatFragmentListener.onEnterToChatDetails();
     }
   } else if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
     if (chatFragmentListener != null) {
       chatFragmentListener.onEnterToChatDetails();
     }
   }
 }
Пример #22
0
  /** 照相获取图片 */
  protected void selectPicFromCamera() {
    if (!EaseCommonUtils.isExitsSdcard()) {
      Toast.makeText(getActivity(), R.string.sd_card_does_not_exist, 0).show();
      return;
    }

    cameraFile =
        new File(
            PathUtil.getInstance().getImagePath(),
            EMClient.getInstance().getCurrentUser() + System.currentTimeMillis() + ".jpg");
    cameraFile.getParentFile().mkdirs();
    startActivityForResult(
        new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
        REQUEST_CODE_CAMERA);
  }
Пример #23
0
  @Override
  protected void onCreate(Bundle arg0) {
    super.onCreate(arg0);
    setContentView(R.layout.activity_pick_at_user);

    String groupId = getIntent().getStringExtra("groupId");
    EMGroup group = EMClient.getInstance().groupManager().getGroup(groupId);
    final ListView listView = (ListView) findViewById(R.id.list);
    List<String> members = group.getMembers();
    List<EaseUser> userList = new ArrayList<EaseUser>();
    for (String username : members) {
      EaseUser user = EaseUserUtils.getUserInfo(username);
      userList.add(user);
    }
    Collections.sort(
        userList,
        new Comparator<EaseUser>() {

          @Override
          public int compare(EaseUser lhs, EaseUser rhs) {
            if (lhs.getInitialLetter().equals(rhs.getInitialLetter())) {
              return lhs.getNick().compareTo(rhs.getNick());
            } else {
              if ("#".equals(lhs.getInitialLetter())) {
                return 1;
              } else if ("#".equals(rhs.getInitialLetter())) {
                return -1;
              }
              return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
            }
          }
        });
    listView.setAdapter(new PickUserAdapter(this, 0, userList));
    listView.setOnItemClickListener(
        new OnItemClickListener() {

          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            EaseUser user = (EaseUser) listView.getItemAtPosition(position);
            if (EMClient.getInstance().getCurrentUser().equals(user.getUsername())) return;
            setResult(Activity.RESULT_OK, new Intent().putExtra("username", user.getUsername()));
            finish();
          }
        });
  }
Пример #24
0
 protected void sendMessage(EMMessage message) {
   if (chatFragmentListener != null) {
     // 设置扩展属性
     chatFragmentListener.onSetMessageAttributes(message);
   }
   // 如果是群聊,设置chattype,默认是单聊
   if (chatType == EaseConstant.CHATTYPE_GROUP) {
     message.setChatType(ChatType.GroupChat);
   } else if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
     message.setChatType(ChatType.ChatRoom);
   }
   // 发送消息
   EMClient.getInstance().chatManager().sendMessage(message);
   // 刷新ui
   if (isMessageListInited) {
     messageList.refreshSelectLast();
   }
 }
Пример #25
0
 protected void onConversationInit() {
   conversation =
       EMClient.getInstance()
           .chatManager()
           .getConversation(toChatUsername, EaseCommonUtils.getConversationType(chatType), true);
   conversation.markAllMessagesAsRead();
   // the number of messages loaded into conversation is getChatOptions().getNumberOfMessagesLoaded
   // you can change this number
   final List<EMMessage> msgs = conversation.getAllMessages();
   int msgCount = msgs != null ? msgs.size() : 0;
   if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
     String msgId = null;
     if (msgs != null && msgs.size() > 0) {
       msgId = msgs.get(0).getMsgId();
     }
     conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
   }
 }
Пример #26
0
 protected void sendMessage(EMMessage message) {
   if (message == null) {
     return;
   }
   if (chatFragmentHelper != null) {
     // set extension
     chatFragmentHelper.onSetMessageAttributes(message);
   }
   if (chatType == EaseConstant.CHATTYPE_GROUP) {
     message.setChatType(ChatType.GroupChat);
   } else if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
     message.setChatType(ChatType.ChatRoom);
   }
   // send message
   EMClient.getInstance().chatManager().sendMessage(message);
   // refresh ui
   if (isMessageListInited) {
     messageList.refreshSelectLast();
   }
 }
Пример #27
0
  protected void onConversationInit() {
    // 获取当前conversation对象

    conversation =
        EMClient.getInstance()
            .chatManager()
            .getConversation(toChatUsername, EaseCommonUtils.getConversationType(chatType), true);
    // 把此会话的未读数置为0
    conversation.markAllMessagesAsRead();
    // 初始化db时,每个conversation加载数目是getChatOptions().getNumberOfMessagesLoaded
    // 这个数目如果比用户期望进入会话界面时显示的个数不一样,就多加载一些
    final List<EMMessage> msgs = conversation.getAllMessages();
    int msgCount = msgs != null ? msgs.size() : 0;
    if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
      String msgId = null;
      if (msgs != null && msgs.size() > 0) {
        msgId = msgs.get(0).getMsgId();
      }
      conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
    }
  }
Пример #28
0
  @Override
  public void Logout() {
    EMClient.getInstance()
        .logout(
            false,
            new EMCallBack() {
              @Override
              public void onSuccess() {
                AVUser.logOut();
                mPreferenceManager.Clear();
                mActivity.startActivity(new Intent(mActivity, SplashActivity.class));
                mActivity.finish();
              }

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

              @Override
              public void onProgress(int i, String s) {}
            });
  }
Пример #29
0
  /** 设置电话监听 */
  void addCallStateListener() {
    callStateListener =
        new EMCallStateChangeListener() {

          @Override
          public void onCallStateChanged(CallState callState, final CallError error) {
            // Message msg = handler.obtainMessage();
            EMLog.d("EMCallManager", "onCallStateChanged:" + callState);
            switch (callState) {
              case CONNECTING: // 正在连接对方
                runOnUiThread(
                    new Runnable() {

                      @Override
                      public void run() {
                        callStateTextView.setText(st1);
                      }
                    });
                break;
              case CONNECTED: // 双方已经建立连接
                runOnUiThread(
                    new Runnable() {

                      @Override
                      public void run() {
                        String st3 = getResources().getString(R.string.have_connected_with);
                        callStateTextView.setText(st3);
                      }
                    });
                break;

              case ACCEPTED: // 电话接通成功
                handler.removeCallbacks(timeoutHangup);
                runOnUiThread(
                    new Runnable() {

                      @Override
                      public void run() {
                        try {
                          if (soundPool != null) soundPool.stop(streamID);
                        } catch (Exception e) {
                        }
                        if (!isHandsfreeState) closeSpeakerOn();
                        // 显示是否为直连,方便测试
                        ((TextView) findViewById(R.id.tv_is_p2p))
                            .setText(
                                EMClient.getInstance().callManager().isDirectCall()
                                    ? R.string.direct_call
                                    : R.string.relay_call);
                        chronometer.setVisibility(View.VISIBLE);
                        chronometer.setBase(SystemClock.elapsedRealtime());
                        // 开始记时
                        chronometer.start();
                        String str4 = getResources().getString(R.string.In_the_call);
                        callStateTextView.setText(str4);
                        callingState = CallingState.NORMAL;
                      }
                    });
                break;
              case NETWORK_UNSTABLE:
                runOnUiThread(
                    new Runnable() {
                      public void run() {
                        netwrokStatusVeiw.setVisibility(View.VISIBLE);
                        if (error == CallError.ERROR_NO_DATA) {
                          netwrokStatusVeiw.setText(R.string.no_call_data);
                        } else {
                          netwrokStatusVeiw.setText(R.string.network_unstable);
                        }
                      }
                    });
                break;
              case NETWORK_NORMAL:
                runOnUiThread(
                    new Runnable() {
                      public void run() {
                        netwrokStatusVeiw.setVisibility(View.INVISIBLE);
                      }
                    });
                break;
              case VOICE_PAUSE:
                runOnUiThread(
                    new Runnable() {
                      public void run() {
                        Toast.makeText(getApplicationContext(), "VOICE_PAUSE", Toast.LENGTH_SHORT)
                            .show();
                      }
                    });
                break;
              case VOICE_RESUME:
                runOnUiThread(
                    new Runnable() {
                      public void run() {
                        Toast.makeText(getApplicationContext(), "VOICE_RESUME", Toast.LENGTH_SHORT)
                            .show();
                      }
                    });
                break;
              case DISCONNNECTED: // 电话断了
                handler.removeCallbacks(timeoutHangup);
                final CallError fError = error;
                runOnUiThread(
                    new Runnable() {
                      private void postDelayedCloseMsg() {
                        handler.postDelayed(
                            new Runnable() {

                              @Override
                              public void run() {
                                runOnUiThread(
                                    new Runnable() {
                                      @Override
                                      public void run() {
                                        Log.d("AAA", "CALL DISCONNETED");
                                        saveCallRecord();
                                        Animation animation = new AlphaAnimation(1.0f, 0.0f);
                                        animation.setDuration(800);
                                        findViewById(R.id.root_layout).startAnimation(animation);
                                        finish();
                                      }
                                    });
                              }
                            },
                            200);
                      }

                      @Override
                      public void run() {
                        chronometer.stop();
                        callDruationText = chronometer.getText().toString();
                        String st2 =
                            getResources().getString(R.string.The_other_party_refused_to_accept);
                        String st3 = getResources().getString(R.string.Connection_failure);
                        String st4 =
                            getResources().getString(R.string.The_other_party_is_not_online);
                        String st5 =
                            getResources().getString(R.string.The_other_is_on_the_phone_please);

                        String st6 =
                            getResources().getString(R.string.The_other_party_did_not_answer_new);
                        String st7 = getResources().getString(R.string.hang_up);
                        String st8 = getResources().getString(R.string.The_other_is_hang_up);

                        String st9 = getResources().getString(R.string.did_not_answer);
                        String st10 = getResources().getString(R.string.Has_been_cancelled);
                        String st11 = getResources().getString(R.string.hang_up);

                        if (fError == CallError.REJECTED) {
                          callingState = CallingState.BEREFUESD;
                          callStateTextView.setText(st2);
                        } else if (fError == CallError.ERROR_TRANSPORT) {
                          callStateTextView.setText(st3);
                        } else if (fError == CallError.ERROR_INAVAILABLE) {
                          callingState = CallingState.OFFLINE;
                          callStateTextView.setText(st4);
                        } else if (fError == CallError.ERROR_BUSY) {
                          callingState = CallingState.BUSY;
                          callStateTextView.setText(st5);
                        } else if (fError == CallError.ERROR_NORESPONSE) {
                          callingState = CallingState.NORESPONSE;
                          callStateTextView.setText(st6);
                        } else if (fError == CallError.ERROR_LOCAL_VERSION_SMALLER
                            || fError == CallError.ERROR_PEER_VERSION_SMALLER) {
                          callingState = CallingState.VERSION_NOT_SAME;
                          callStateTextView.setText(R.string.call_version_inconsistent);
                        } else {
                          if (isAnswered) {
                            callingState = CallingState.NORMAL;
                            if (endCallTriggerByMe) {
                              //
                              // callStateTextView.setText(st7);
                            } else {
                              callStateTextView.setText(st8);
                            }
                          } else {
                            if (isInComingCall) {
                              callingState = CallingState.UNANSWERED;
                              callStateTextView.setText(st9);
                            } else {
                              if (callingState != CallingState.NORMAL) {
                                callingState = CallingState.CANCED;
                                callStateTextView.setText(st10);
                              } else {
                                callStateTextView.setText(st11);
                              }
                            }
                          }
                        }
                        postDelayedCloseMsg();
                      }
                    });

                break;

              default:
                break;
            }
          }
        };
    EMClient.getInstance().callManager().addCallStateChangeListener(callStateListener);
  }
Пример #30
0
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
      convertView =
          LayoutInflater.from(getContext()).inflate(R.layout.ease_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_itease_layout =
          (RelativeLayout) convertView.findViewById(R.id.list_itease_layout);
      convertView.setTag(holder);
    }
    holder.list_itease_layout.setBackgroundResource(R.drawable.ease_mm_listitem);

    // 获取与此用户/群组的会话
    EMConversation conversation = getItem(position);
    // 获取用户username或者群组groupid
    String username = conversation.getUserName();

    if (conversation.getType() == EMConversationType.GroupChat) {
      // 群聊消息,显示群聊头像
      holder.avatar.setImageResource(R.drawable.ease_group_icon);
      EMGroup group = EMClient.getInstance().groupManager().getGroup(username);
      holder.name.setText(group != null ? group.getGroupName() : username);
    } else if (conversation.getType() == EMConversationType.ChatRoom) {
      holder.avatar.setImageResource(R.drawable.ease_group_icon);
      EMChatRoom room = EMClient.getInstance().chatroomManager().getChatRoom(username);
      holder.name.setText(
          room != null && !TextUtils.isEmpty(room.getName()) ? room.getName() : username);
    } else {
      EaseUserUtils.setUserAvatar(getContext(), username, holder.avatar);
      EaseUserUtils.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.getAllMsgCount() != 0) {
      // 把最后一条消息的内容作为item的message内容
      EMMessage lastMessage = conversation.getLastMessage();
      holder.message.setText(
          EaseSmileUtils.getSmiledText(
              getContext(), EaseCommonUtils.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);
      }
    }

    // 设置自定义属性
    holder.name.setTextColor(primaryColor);
    holder.message.setTextColor(secondaryColor);
    holder.time.setTextColor(timeColor);
    if (primarySize != 0) holder.name.setTextSize(TypedValue.COMPLEX_UNIT_PX, primarySize);
    if (secondarySize != 0) holder.message.setTextSize(TypedValue.COMPLEX_UNIT_PX, secondarySize);
    if (timeSize != 0) holder.time.setTextSize(TypedValue.COMPLEX_UNIT_PX, timeSize);

    return convertView;
  }