Beispiel #1
0
 private void initListener() {
   Intent intent = getIntent();
   String username = intent.getStringExtra("username");
   boolean enableUpdate = intent.getBooleanExtra("setting", false);
   if (enableUpdate) {
     headPhotoUpdate.setVisibility(View.VISIBLE);
     iconRightArrow.setVisibility(View.VISIBLE);
     rlNickName.setOnClickListener(this);
     headAvatar.setOnClickListener(this);
   } else {
     headPhotoUpdate.setVisibility(View.GONE);
     iconRightArrow.setVisibility(View.INVISIBLE);
   }
   if (username != null) {
     if (username.equals(EMChatManager.getInstance().getCurrentUser())) {
       tvUsername.setText(EMChatManager.getInstance().getCurrentUser());
       EaseUserUtils.setUserNick(username, tvNickName);
       EaseUserUtils.setUserAvatar(this, username, headAvatar);
     } else {
       tvUsername.setText(username);
       EaseUserUtils.setUserNick(username, tvNickName);
       EaseUserUtils.setUserAvatar(this, username, headAvatar);
       asyncFetchUserInfo(username);
     }
   }
 }
 /**
  * 获取未读消息数
  *
  * @return
  */
 public int getUnreadMsgCountTotal() {
   int unreadMsgCountTotal = 0;
   int chatroomUnreadMsgCount = 0;
   unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
   for (EMConversation conversation : EMChatManager.getInstance().getAllConversations().values()) {
     if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
       chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
   }
   return unreadMsgCountTotal - chatroomUnreadMsgCount;
 }
  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) {
    }
  }
Beispiel #4
0
  public boolean onOptionsItemSelected(MenuItem item) {
    if (drawerToggle.onOptionsItemSelected(item)) return true;

    int id = item.getItemId();
    switch (id) {
      case R.id.logoutMenuItem:
        EMChatManager.getInstance().logout();
        databaseUtil.deleteAllDatabases();
        SharedPreferences.Editor editor =
            getSharedPreferences("login_info", android.content.Context.MODE_PRIVATE).edit();
        editor.putBoolean("state", false);
        editor.commit();
        Intent intent = new Intent(MainActivity.this, StartActivity.class);
        startActivity(intent);
        finish();
        return true;

      case R.id.exitMenuItem:
        MyApplication.finishAllActivity();
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }
  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);
    }
  }
  /** init HuanXin listeners */
  protected void initListener() {
    Log.d(TAG, "init listener");

    // create the global connection listener
    connectionListener =
        new EMConnectionListener() {
          @Override
          public void onDisconnected(int error) {
            if (error == EMError.USER_REMOVED) {
              onCurrentAccountRemoved();
            } else if (error == EMError.CONNECTION_CONFLICT) {
              onConnectionConflict();
            } else {
              onConnectionDisconnected(error);
            }
          }

          @Override
          public void onConnected() {
            onConnectionConnected();
          }
        };

    // 注册连接监听
    EMChatManager.getInstance().addConnectionListener(connectionListener);
  }
  /** logout HuanXin SDK */
  public void logout(final boolean unbindDeviceToken, final EMCallBack callback) {
    setPassword(null);
    reset();
    EMChatManager.getInstance()
        .logout(
            unbindDeviceToken,
            new EMCallBack() {

              @Override
              public void onSuccess() {
                if (callback != null) {
                  callback.onSuccess();
                }
              }

              @Override
              public void onError(int code, String message) {
                if (callback != null) {
                  callback.onError(code, message);
                }
              }

              @Override
              public void onProgress(int progress, String status) {
                if (callback != null) {
                  callback.onProgress(progress, status);
                }
              }
            });
  }
  @Override
  public boolean onContextItemSelected(MenuItem item) {
    boolean handled = false;
    boolean deleteMessage = false;
    if (item.getItemId() == R.id.delete_message) {
      deleteMessage = true;
      handled = true;
    } else if (item.getItemId() == R.id.delete_conversation) {
      deleteMessage = false;
      handled = true;
    }
    EMConversation tobeDeleteCons =
        adapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
    // 删除此会话
    EMChatManager.getInstance()
        .deleteConversation(tobeDeleteCons.getUserName(), tobeDeleteCons.isGroup(), deleteMessage);
    InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(getActivity());
    inviteMessgeDao.deleteMessage(tobeDeleteCons.getUserName());
    adapter.remove(tobeDeleteCons);
    adapter.notifyDataSetChanged();

    // 更新消息未读数
    ((MainActivity) getActivity()).updateUnreadLabel();

    return handled ? true : super.onContextItemSelected(item);
  }
  @Override
  protected void onStop() {
    EMChatManager.getInstance().unregisterEventListener(this);
    DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper.getInstance();

    super.onStop();
  }
 public boolean updateParseNickName(final String nickname) {
   String username = EMChatManager.getInstance().getCurrentUser();
   ParseQuery<ParseObject> pQuery = ParseQuery.getQuery(CONFIG_TABLE_NAME);
   pQuery.whereEqualTo(CONFIG_USERNAME, username);
   ParseObject pUser = null;
   try {
     pUser = pQuery.getFirst();
     if (pUser == null) {
       return false;
     }
     pUser.put(CONFIG_NICK, nickname);
     pUser.save();
     return true;
   } catch (ParseException e) {
     if (e.getCode() == ParseException.OBJECT_NOT_FOUND) {
       pUser = new ParseObject(CONFIG_TABLE_NAME);
       pUser.put(CONFIG_USERNAME, username);
       pUser.put(CONFIG_NICK, nickname);
       try {
         pUser.save();
         return true;
       } catch (ParseException e1) {
         e1.printStackTrace();
         EMLog.e(TAG, "parse error " + e1.getMessage());
       }
     }
     e.printStackTrace();
     EMLog.e(TAG, "parse error " + e.getMessage());
   }
   return false;
 }
 /**
  * 获取所有会话
  *
  * @return
  */
 private List<EMConversation> loadConversationsWithRecentChat() {
   // 获取所有会话,包括陌生人
   Hashtable<String, EMConversation> conversations =
       EMChatManager.getInstance().getAllConversations();
   // 过滤掉messages size为0的conversation
   /**
    * 如果在排序过程中有新消息收到,lastMsgTime会发生变化 影响排序过程,Collection.sort会产生异常 保证Conversation在Sort过程中最后一条消息的时间不变
    * 避免并发问题
    */
   List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
   synchronized (conversations) {
     for (EMConversation conversation : conversations.values()) {
       if (conversation.getAllMessages().size() != 0) {
         // if(conversation.getType() != EMConversationType.ChatRoom){
         sortList.add(
             new Pair<Long, EMConversation>(
                 conversation.getLastMessage().getMsgTime(), conversation));
         // }
       }
     }
   }
   try {
     sortConversationByLastChatTime(sortList);
   } catch (Exception e) {
     e.printStackTrace();
   }
   List<EMConversation> list = new ArrayList<EMConversation>();
   for (Pair<Long, EMConversation> sortItem : sortList) {
     list.add(sortItem.second);
   }
   return list;
 }
  public void asyncGetCurrentUserInfo(final EMValueCallBack<User> callback) {
    final String username = EMChatManager.getInstance().getCurrentUser();
    asyncGetUserInfo(
        username,
        new EMValueCallBack<User>() {

          @Override
          public void onSuccess(User value) {
            callback.onSuccess(value);
          }

          @Override
          public void onError(int error, String errorMsg) {
            if (error == ParseException.OBJECT_NOT_FOUND) {
              ParseObject pUser = new ParseObject(CONFIG_TABLE_NAME);
              pUser.put(CONFIG_USERNAME, username);
              pUser.saveInBackground(
                  new SaveCallback() {

                    @Override
                    public void done(ParseException arg0) {
                      if (arg0 == null) {
                        callback.onSuccess(new User(username));
                      }
                    }
                  });
            } else {
              callback.onError(error, errorMsg);
            }
          }
        });
  }
    @Override
    protected String doInBackground(String... arg0) {
      // TODO Auto-generated method stub
      String userid = arg0[0];
      String pwd = arg0[1];

      try {
        Log.i(TAG, "注册账户:" + userid + ":" + pwd);
        EMChatManager.getInstance().createAccountOnServer(userid, pwd);
        Log.i(TAG, "注册账户成功");
      } catch (EaseMobException e) {
        // TODO Auto-generated catch block
        final String erro = e.toString();
        runOnUiThread(
            new Runnable() {

              @Override
              public void run() {
                // TODO Auto-generated method stub
                Toast.makeText(LoginActivity.this, "注册失败" + erro, Toast.LENGTH_SHORT).show();
              }
            });
        e.printStackTrace();
        Log.i(TAG, "注册账户失败");
        CustomConfigManager.getInstance().setFLAG(true);
      }
      return userid;
    }
 private void refreshExit(String result) {
   EMChatManager.getInstance().logout();
   ShareSDK.stopSDK(this);
   Intent intent = new Intent(this, IfanService.class);
   stopService(intent);
   android.os.Process.killProcess(android.os.Process.myPid());
 }
Beispiel #15
0
 void endCall() {
   try {
     EMChatManager.getInstance().endCall();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 @Override
 public void onBackPressed() {
   EMChatManager.getInstance().endCall();
   callDruationText = chronometer.getText().toString();
   saveCallRecord(1);
   finish();
 }
 /** 注册监听 */
 private void initMessageReceiver() {
   msgReceiver = new NewMessageBroadcastReceiver();
   IntentFilter intentFilter =
       new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
   intentFilter.setPriority(3);
   registerReceiver(msgReceiver, intentFilter);
 }
 public String uploadParseAvatar(byte[] data) {
   String username = EMChatManager.getInstance().getCurrentUser();
   ParseQuery<ParseObject> pQuery = ParseQuery.getQuery(CONFIG_TABLE_NAME);
   pQuery.whereEqualTo(CONFIG_USERNAME, username);
   ParseObject pUser = null;
   try {
     pUser = pQuery.getFirst();
     if (pUser == null) {
       pUser = new ParseObject(CONFIG_TABLE_NAME);
       pUser.put(CONFIG_USERNAME, username);
     }
     ParseFile pFile = new ParseFile(data);
     pUser.put(CONFIG_AVATAR, pFile);
     pUser.save();
     return pFile.getUrl();
   } catch (ParseException e) {
     if (e.getCode() == ParseException.OBJECT_NOT_FOUND) {
       try {
         pUser = new ParseObject(CONFIG_TABLE_NAME);
         pUser.put(CONFIG_USERNAME, username);
         ParseFile pFile = new ParseFile(data);
         pUser.put(CONFIG_AVATAR, pFile);
         pUser.save();
         return pFile.getUrl();
       } catch (ParseException e1) {
         e1.printStackTrace();
         EMLog.e(TAG, "parse error " + e1.getMessage());
       }
     } else {
       e.printStackTrace();
       EMLog.e(TAG, "parse error " + e.getMessage());
     }
   }
   return null;
 }
Beispiel #19
0
  private void logOut() {
    EMChatManager.getInstance()
        .logout(
            new EMCallBack() {

              @Override
              public void onSuccess() {
                Log.d("LOGOUT", "环信登出成功!");
                System.err.println("环信登出成功!");

                SharedPreferences sp = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
                Editor userInfo_Editor = sp.edit();
                userInfo_Editor.putBoolean("isLogin", false);
                userInfo_Editor.commit();
                Message msg = new Message();
                msg.what = 1;
                handler.sendMessage(msg);
              }

              @Override
              public void onProgress(int progress, String status) {}

              @Override
              public void onError(int code, String message) {
                Log.d("LOGOUT", "环信登出失败!" + message);
                System.err.println("环信登出失败!" + message);
              }
            });
  }
Beispiel #20
0
  /** logout HuanXin SDK */
  public void logout(final EMCallBack callback) {
    EMChatManager.getInstance()
        .logout(
            new EMCallBack() {

              @Override
              public void onSuccess() {
                // TODO Auto-generated method stub
                setPassword(null);
                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);
                }
              }
            });
  }
Beispiel #21
0
  @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());
  }
 private void showGroupDetail() {
   progressBar.setVisibility(View.INVISIBLE);
   // 获取详情成功,并且自己不在群中,才让加入群聊按钮可点击
   if (!group.getMembers().contains(EMChatManager.getInstance().getCurrentUser()))
     btn_add_group.setEnabled(true);
   tv_name.setText(group.getGroupName());
   tv_admin.setText(group.getOwner());
   tv_introduction.setText(group.getDescription());
 }
 /** 初始化视频请求监听 */
 private void initCallListener() {
   IntentFilter callFilter =
       new IntentFilter(EMChatManager.getInstance().getIncomingCallBroadcastAction());
   if (callReceiver == null) {
     callReceiver = new CallReceiver();
   }
   // 注册通话广播接收者
   registerReceiver(callReceiver, callFilter);
 }
Beispiel #24
0
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if (resultCode == RESULT_OK) {
     if (requestCode == REQUEST_CODE_EMPTY_HISTORY) {
       EMChatManager.getInstance().clearConversation(toChatUsername);
     }
   }
 }
Beispiel #25
0
 @Override
 public void onClick(DialogInterface dialog, int which) {
   EMConversation conversation = conversationList.get(deleteID);
   EMChatManager.getInstance().deleteConversation(conversation.getUserName());
   // Utils.showLongToast((Activity) context, "删除成功");
   conversationList.remove(deleteID);
   notifyDataSetChanged();
   Tipdialog.dismiss();
 }
 public void updateUrmCount() {
   int urmCount = EMChatManager.getInstance().getUnreadMsgsCount();
   if (urmCount > 0) {
     textViews[INDEX_INFO].setText(String.valueOf(urmCount));
     textViews[INDEX_INFO].setVisibility(View.VISIBLE);
   } else {
     textViews[INDEX_INFO].setVisibility(View.INVISIBLE);
   }
 }
Beispiel #27
0
  /**
   * 保存通话消息记录
   *
   * @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);
  }
  @Override
  public void initView() {
    tabHost = (TabHost) findViewById(android.R.id.tabhost);
    tabHost.setup(getLocalActivityManager());
    MyOnClickListener listener = new MyOnClickListener();
    for (int i = 0; i < hpClasses.length; i++) {
      TabSpec spec =
          tabHost
              .newTabSpec(tabs[i])
              .setIndicator(tabs[i])
              .setContent(new Intent(this, hpClasses[i]));
      tabHost.addTab(spec);
      buttons[i] = (Button) findViewById(btnIds[i]);
      buttons[i].setOnClickListener(listener);
      textViews[i] = (TextView) findViewById(txtIds[i]);
    }
    buttons[INDEX_FIND].setSelected(true);
    curIndex = INDEX_FIND;

    // 注册一个接收消息的BroadcastReceiver
    nmReceiver = new NewMessageBroadcastReceiver();
    IntentFilter intentFilter =
        new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
    intentFilter.setPriority(3);
    registerReceiver(nmReceiver, intentFilter);

    // 注册一个ack回执消息的BroadcastReceiver
    amReceiver = new AckMessageReceiver();
    IntentFilter ackMessageIntentFilter =
        new IntentFilter(EMChatManager.getInstance().getAckMessageBroadcastAction());
    ackMessageIntentFilter.setPriority(3);
    registerReceiver(amReceiver, ackMessageIntentFilter);

    // 注册一个监听连接状态的listener
    EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());

    // 通知sdk,UI 已经初始化完毕,注册了相应的receiver, 可以接受broadcast了
    EMChat.getInstance().setAppInited();

    niReceiver = new NewInfoReceiver();
    IntentFilter niIntentFilter = new IntentFilter(IntentString.Receiver.NEW_INFO);
    registerReceiver(niReceiver, niIntentFilter);
  }
 @Override
 protected void onStart() {
   // TODO Auto-generated method stub
   super.onStart();
   IntentFilter intentFilter =
       new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
   intentFilter.setPriority(5);
   registerReceiver(msgReceiver, intentFilter);
   EMChat.getInstance().setAppInited();
 }
Beispiel #30
0
  private void initEMChat() {
    int pid = android.os.Process.myPid();
    String processAppName = getAppName(pid);
    if (processAppName == null || !processAppName.equalsIgnoreCase("com.juns.wechat")) {
      return;
    }
    EMChatOptions options = EMChatManager.getInstance().getChatOptions();
    // 获取到EMChatOptions对象
    // 设置自定义的文字提示
    options.setNotifyText(
        new OnMessageNotifyListener() {

          @Override
          public String onNewMessageNotify(EMMessage message) {
            return "你的好友发来了一条消息哦";
          }

          @Override
          public String onLatestMessageNotify(EMMessage message, int fromUsersNum, int messageNum) {
            return fromUsersNum + "个好友,发来了" + messageNum + "条消息";
          }

          @Override
          public String onSetNotificationTitle(EMMessage arg0) {
            return null;
          }

          @Override
          public int onSetSmallIcon(EMMessage arg0) {
            return 0;
          }
        });
    options.setOnNotificationClickListener(
        new OnNotificationClickListener() {

          @Override
          public Intent onNotificationClick(EMMessage message) {
            Intent intent = new Intent(_context, MainActivity.class);
            ChatType chatType = message.getChatType();
            if (chatType == ChatType.Chat) { // 单聊信息
              intent.putExtra("userId", message.getFrom());
              intent.putExtra("chatType", ChatActivity.CHATTYPE_SINGLE);
            } else { // 群聊信息
              // message.getTo()为群聊id
              intent.putExtra("groupId", message.getTo());
              intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
            }
            return intent;
          }
        });
    // IntentFilter callFilter = new
    // IntentFilter(EMChatManager.getInstance()
    // .getIncomingCallBroadcastAction());
    // registerReceiver(new CallReceiver(), callFilter);
  }