13、MainActivity
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.huanxin.adapter.MyFriendListAdapter;
import com.example.huanxin.utils.SpUtil;
import com.example.huanxin.utils.ToastUtil;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TextView user_name;
private RecyclerView recyclerview;
private ArrayList<String> recyclerviewList;
private MyFriendListAdapter myFriendListAdapter;
private String mName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iniPer();
initView();
initFriend();
}
// 运行时权限,这里没有判断是否有权限,自己可以添加判断
private void iniPer() {
String[] per = {Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_PHONE_STATE};
ActivityCompat.requestPermissions(this, per, 100);
}
private void initView() {
user_name = (TextView) findViewById(R.id.user_name);
recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
mName = (String) SpUtil.getParam(Constants.NAME, "没有登陆成功");
user_name.setText("当前用户:" + mName);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerview.setLayoutManager(layoutManager);
recyclerview.addItemDecoration(new DividerItemDecoration(ChatActivity.this,DividerItemDecoration.VERTICAL));
recyclerviewList = new ArrayList<>();
myFriendListAdapter = new MyFriendListAdapter(recyclerviewList, MainActivity.this);
recyclerview.setAdapter(myFriendListAdapter);
myFriendListAdapter.setOnItemClickListener(new MyFriendListAdapter.OnItemClickListener() {
@Override
public void onItemClick(String name) {
goChatActivity(name);
}
});
}
private void goChatActivity(String name) {
Intent intent = new Intent(MainActivity.this, ChatActivity.class);
intent.putExtra(Constants.NAME,name);
intent.putExtra(Constants.MName,mName);
startActivity(intent);
}
// 加载好友
private void initFriend() {
new Thread(new Runnable() {
@Override
public void run() {
try {
List<String> usernames = EMClient.getInstance().contactManager().getAllContactsFromServer();
recyclerviewList.clear();
recyclerviewList.addAll(usernames);
runOnUiThread(new Runnable() {
@Override
public void run() {
myFriendListAdapter.notifyDataSetChanged();
}
});
} catch (HyphenateException e) {
e.printStackTrace();
}
}
}).start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(1, 1, 0, "退出登录");
menu.add(1, 2, 0, "进入群聊");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
logout();
break;
case 2:
Intent intent = new Intent(MainActivity.this, GroupChatActivity.class);
intent.putExtra(Constants.MName,mName);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
EMClient.getInstance().logout(true, new EMCallBack() {
@Override
public void onSuccess() {
// TODO Auto-generated method stub
showToast("退出登陆成功");
SpUtil.setParam(Constants.NAME, "");
goLoginActivity();
}
@Override
public void onProgress(int progress, String status) {
// TODO Auto-generated method stub
}
@Override
public void onError(int code, String message) {
// TODO Auto-generated method stub
showToast("退出登陆失败");
}
});
}
private void goLoginActivity() {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
private void showToast(final String string) {
runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtil.showShort(string);
}
});
}
}
adapter
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.huanxin.R;
import java.util.ArrayList;
public class MyFriendListAdapter extends RecyclerView.Adapter<MyFriendListAdapter.ViewHolder> {
private ArrayList<String> recyclerviewList;
Context context;
public MyFriendListAdapter(ArrayList<String> recyclerviewList, Context context) {
this.recyclerviewList = recyclerviewList;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.friendlist_item, null);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
final String s = recyclerviewList.get(i);
viewHolder.user_name.setText(s);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onItemClickListener!=null){
onItemClickListener.onItemClick(s);
}
}
});
}
@Override
public int getItemCount() {
return recyclerviewList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView user_name;
public ViewHolder(@NonNull View itemView) {
super(itemView);
user_name=itemView.findViewById(R.id.user_name);
}
}
OnItemClickListener onItemClickListener;
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public interface OnItemClickListener{
void onItemClick(String name);
}
}
friendlist_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical">
<ImageView
android:id="@+id/head_portrait"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@mipmap/ic_launcher_round"
android:layout_marginRight="10dp"/>
<TextView
android:id="@+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
14、ChatActivity(聊天界面)
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChatActivity"
android:orientation="vertical">
<TextView
android:id="@+id/user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp">
</android.support.v7.widget.RecyclerView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/et_msg"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/send_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/record_voice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始录音"/>
<Button
android:id="@+id/send_voice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送语音"/>
</LinearLayout>
</LinearLayout>
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.huanxin.adapter.MyChatAdapter;
import com.example.huanxin.utils.AudioUtil;
import com.example.huanxin.utils.ToastUtil;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ChatActivity extends AppCompatActivity implements View.OnClickListener {
private TextView user_name;
private RecyclerView recyclerview;
private EditText et_msg;
private Button send_msg;
private String name;
private ArrayList<EMMessage> recyclerviewList;
private MyChatAdapter myChatAdapter;
private Button record_voice;
private Button send_voice;
private String mPath;
private long mDuration;
private MediaPlayer mediaPlayer;
private String mName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
name = getIntent().getStringExtra(Constants.NAME);
mName = getIntent().getStringExtra(Constants.MName);
initView();
receiveMsg();
}
private void initView() {
user_name = (TextView) findViewById(R.id.user_name);
recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
et_msg = (EditText) findViewById(R.id.et_msg);
send_msg = (Button) findViewById(R.id.send_msg);
record_voice = (Button) findViewById(R.id.record_voice);
send_voice = (Button) findViewById(R.id.send_voice);
send_msg.setOnClickListener(this);
record_voice.setOnClickListener(this);
send_voice.setOnClickListener(this);
user_name.setText("正在和:" + name + " 聊天");
LinearLayoutManager layoutManager = new LinearLayoutManager(ChatActivity.this);
recyclerview.setLayoutManager(layoutManager);
recyclerview.addItemDecoration(new DividerItemDecoration(ChatActivity.this,DividerItemDecoration.VERTICAL));
recyclerviewList = new ArrayList<>();
myChatAdapter = new MyChatAdapter(recyclerviewList, ChatActivity.this,mName);
recyclerview.setAdapter(myChatAdapter);
myChatAdapter.setOnItemClickListener(new MyChatAdapter.OnItemClickListener() {
@Override
public void onItemClick(String path) {
if (!TextUtils.isEmpty(path)){
playVoice(path);
}
}
});
}
// 播放语音
private void playVoice(String path) {
if (mediaPlayer!=null){
mediaPlayer.reset();
}else {
mediaPlayer = new MediaPlayer();
}
try {
//mediaPlayer.prepareAsync();
if (mediaPlayer.isPlaying()){
mediaPlayer.pause();
}else {
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.send_msg:
submit();
break;
case R.id.record_voice:
//当前是否是在录音
if (AudioUtil.isRecording){
AudioUtil.stopRecord();
record_voice.setText("开始录音");
}else {
startVoice();
record_voice.setText("停止录音");
}
break;
case R.id.send_voice:
sendVoice();
break;
}
}
private void startVoice() {
AudioUtil.startRecord(new AudioUtil.ResultCallBack() {
@Override
public void onSuccess(String path, long time) {
mPath = path;
mDuration = time;
}
@Override
public void onFail(String msg) {
showToast("录音失败");
}
});
}
private void sendVoice() {
if (mPath.isEmpty()){
showToast("没有");
}
new Thread(new Runnable() {
@Override
public void run() {
//filePath为语音文件路径,length为录音时间(秒)
EMMessage message = EMMessage.createVoiceSendMessage(mPath, (int) mDuration, name);
//如果是群聊,设置chattype,默认是单聊
// if (chatType == CHATTYPE_GROUP)
// message.setChatType(ChatType.GroupChat);
EMClient.getInstance().chatManager().sendMessage(message);
addAdapterList(message);
}
}).start();
}
private void submit() {
// validate
final String msg = et_msg.getText().toString().trim();
if (TextUtils.isEmpty(msg)) {
showToast("内容不能为空");
return;
}
// TODO validate success, do something
new Thread(new Runnable() {
@Override
public void run() {
//创建一条文本消息,content为消息文字内容,toChatUsername为对方用户或者群聊的id,后文皆是如此
EMMessage message = EMMessage.createTxtSendMessage(msg, name);
//如果是群聊,设置chattype,默认是单聊
// if (chatType == CHATTYPE_GROUP)
// message.setChatType(ChatType.GroupChat);
//发送消息
EMClient.getInstance().chatManager().sendMessage(message);
addAdapterList(message);
}
}).start();
// 让编辑框清空
et_msg.setText("");
}
// 把聊天内容发送到Recyclerview上显示
private void addAdapterList(EMMessage message) {
recyclerviewList.add(message);
runOnUiThread(new Runnable() {
@Override
public void run() {
myChatAdapter.notifyDataSetChanged();
// Recyclerview 一直显示最后一条信息
recyclerview.scrollToPosition(recyclerviewList.size() - 1);
}
});
}
private void showToast(final String msg) {
runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtil.showShort(msg);
}
});
}
private void receiveMsg() {
//记得在不需要的时候移除listener,如在activity的onDestroy()时
EMClient.getInstance().chatManager().addMessageListener(msgListener);
}
// 通过注册消息监听来接收消息
EMMessageListener msgListener = new EMMessageListener() {
@Override
public void onMessageReceived(List<EMMessage> messages) {
//收到消息
if (messages != null && messages.size() > 0) {
final ArrayList<EMMessage> list = new ArrayList<>();
for (EMMessage msg : messages) {
String from = msg.getFrom();
if (from.equals(name)) {
list.add(msg);
}
}
runOnUiThread(new Runnable() {
@Override
public void run() {
recyclerviewList.addAll(list);
myChatAdapter.notifyDataSetChanged();
recyclerview.scrollToPosition(recyclerviewList.size() - 1);
}
});
}
}
@Override
public void onCmdMessageReceived(List<EMMessage> messages) {
//收到透传消息
}
@Override
public void onMessageRead(List<EMMessage> messages) {
//收到已读回执
}
@Override
public void onMessageDelivered(List<EMMessage> message) {
//收到已送达回执
}
@Override
public void onMessageRecalled(List<EMMessage> messages) {
//消息被撤回
}
@Override
public void onMessageChanged(EMMessage message, Object change) {
//消息状态变动
}
};
@Override
protected void onDestroy() {
super.onDestroy();
EMClient.getInstance().chatManager().removeMessageListener(msgListener);
}
}
adapter
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.huanxin.R;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessageBody;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MyChatAdapter extends RecyclerView.Adapter<MyChatAdapter.ViewHolder> {
private ArrayList<EMMessage> recyclerviewList;
Context context;
private String mName;
public MyChatAdapter(ArrayList<EMMessage> recyclerviewList, Context context, String mName) {
this.recyclerviewList = recyclerviewList;
this.context = context;
this.mName = mName;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.chat_item, null);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
EMMessage emMessage = recyclerviewList.get(i);
String from = emMessage.getFrom();
EMMessageBody body = emMessage.getBody();
long msgTime = emMessage.getMsgTime();
String formatTime = formatTime(msgTime);
viewHolder.time.setText(formatTime);
viewHolder.user_name.setText("来自:" + from + " 的消息" );
viewHolder.muser_name.setText("来自:" + from + " 的消息");
if (from.equals(mName)) {
viewHolder.right_Layout.setVisibility(View.VISIBLE);
viewHolder.left_layout.setVisibility(View.GONE);
viewHolder.mcontent.setText(body.toString());
} else {
viewHolder.right_Layout.setVisibility(View.GONE);
viewHolder.left_layout.setVisibility(View.VISIBLE);
viewHolder.content.setText(body.toString());
}
viewHolder.content.setText(body.toString());
String path = "";
String[] split = body.toString().split(",");
for (int j = 0; j < split.length; j++) {
String s = split[j];
if (s.startsWith("localurl")){
String[] split1 = s.split(":");
String s1 = split1[1];
path = s1;
}
}
final String finalPath = path;
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(finalPath);
}
}
});
}
private String formatTime(long msgTime) {
Date date = new Date(msgTime);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
return simpleDateFormat.format(date);
}
@Override
public int getItemCount() {
return recyclerviewList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView user_name;
private TextView content;
private LinearLayout left_layout;
private TextView muser_name;
private TextView mcontent;
private LinearLayout right_Layout;
private TextView time;
public ViewHolder(@NonNull View itemView) {
super(itemView);
user_name = itemView.findViewById(R.id.user_name);
content = itemView.findViewById(R.id.content);
left_layout = itemView.findViewById(R.id.left_layout);
muser_name = itemView.findViewById(R.id.muser_name);
mcontent = itemView.findViewById(R.id.mcontent);
right_Layout = itemView.findViewById(R.id.right_Layout);
time = itemView.findViewById(R.id.time);
}
}
OnItemClickListener onItemClickListener;
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public interface OnItemClickListener {
void onItemClick(String path);
}
}
chat_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="123"/>
<LinearLayout
android:id="@+id/left_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentLeft="true"
android:layout_below="@id/time">
<TextView
android:id="@+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="user_name"/>
<TextView
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="content"/>
</LinearLayout>
<LinearLayout
android:id="@+id/right_Layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentRight="true"
android:gravity="right"
android:layout_below="@id/left_layout">
<TextView
android:id="@+id/muser_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="user_name"
android:gravity="right"/>
<TextView
android:id="@+id/mcontent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="content"/>
</LinearLayout>
</RelativeLayout>
15、GroupChatActivity(群聊界面)
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".GroupChatActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/create_gruopname"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/create_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="创建群聊"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/join_gruopname"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/join_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="加入群聊"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp">
</android.support.v7.widget.RecyclerView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/et_msg"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/send_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/record_voice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始录音"/>
<Button
android:id="@+id/send_voice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送语音"/>
</LinearLayout>
</LinearLayout>
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.huanxin.adapter.MyChatAdapter;
import com.example.huanxin.utils.AudioUtil;
import com.example.huanxin.utils.ToastUtil;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMGroupManager;
import com.hyphenate.chat.EMGroupOptions;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class GroupChatActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "GroupChatActivity";
private EditText create_gruopname;
private Button create_group;
private EditText join_gruopname;
private Button join_group;
private RecyclerView recyclerview;
private EditText et_msg;
private Button send_msg;
private Button record_voice;
private Button send_voice;
private ArrayList<EMMessage> recyclerviewList;
private MyChatAdapter myChatAdapter;
//群组的id
private String gruopname;
private String mPath;
private long mDuration;
private MediaPlayer mediaPlayer;
private String mName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_chat);
mName = getIntent().getStringExtra(Constants.MName);
initView();
receiveMsg();
}
private void initView() {
create_gruopname = (EditText) findViewById(R.id.create_gruopname);
create_group = (Button) findViewById(R.id.create_group);
join_gruopname = (EditText) findViewById(R.id.join_gruopname);
join_group = (Button) findViewById(R.id.join_group);
recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
et_msg = (EditText) findViewById(R.id.et_msg);
send_msg = (Button) findViewById(R.id.send_msg);
record_voice = (Button) findViewById(R.id.record_voice);
send_voice = (Button) findViewById(R.id.send_voice);
create_group.setOnClickListener(this);
join_group.setOnClickListener(this);
send_msg.setOnClickListener(this);
record_voice.setOnClickListener(this);
send_voice.setOnClickListener(this);
LinearLayoutManager layoutManager = new LinearLayoutManager(GroupChatActivity.this);
recyclerview.setLayoutManager(layoutManager);
recyclerview.addItemDecoration(new DividerItemDecoration(GroupChatActivity.this,DividerItemDecoration.VERTICAL));
recyclerviewList = new ArrayList<>();
myChatAdapter = new MyChatAdapter(recyclerviewList, GroupChatActivity.this,mName);
recyclerview.setAdapter(myChatAdapter);
myChatAdapter.setOnItemClickListener(new MyChatAdapter.OnItemClickListener() {
@Override
public void onItemClick(String path) {
if (!TextUtils.isEmpty(path)){
playVoice(path);
}
}
});
}
// 播放语音
private void playVoice(String path) {
if (mediaPlayer!=null){
mediaPlayer.reset();
}else {
mediaPlayer = new MediaPlayer();
}
try {
//mediaPlayer.prepareAsync();
if (mediaPlayer.isPlaying()){
mediaPlayer.pause();
}else {
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.create_group:
createGroup();
break;
case R.id.join_group:
joinGroup();
break;
case R.id.send_msg:
submit();
break;
case R.id.record_voice:
//当前是否是在录音
if (AudioUtil.isRecording){
AudioUtil.stopRecord();
record_voice.setText("开始录音");
}else {
startVoice();
record_voice.setText("停止录音");
}
break;
case R.id.send_voice:
sendVoice();
break;
}
}
private void createGroup() {
final String gruopname = create_gruopname.getText().toString().trim();
if (TextUtils.isEmpty(gruopname)) {
showToast("群聊的id不能为空");
return;
}
new Thread(new Runnable() {
@Override
public void run() {
/**
* 创建群组
* @param groupName 群组名称
* @param desc 群组简介
* @param allMembers 群组初始成员,如果只有自己传空数组即可
* @param reason 邀请成员加入的reason
* @param option 群组类型选项,可以设置群组最大用户数(默认200)及群组类型@see {@link EMGroupStyle}
* option.inviteNeedConfirm表示邀请对方进群是否需要对方同意,默认是需要用户同意才能加群的。
* option.extField创建群时可以为群组设定扩展字段,方便个性化订制。
* @return 创建好的group
* @throws HyphenateException
*/
EMGroupOptions option = new EMGroupOptions();
option.maxUsers = 200;
option.style = EMGroupManager.EMGroupStyle.EMGroupStylePublicOpenJoin;
try {
EMGroup group = EMClient.getInstance().groupManager().createGroup(gruopname, "聊天", new String[]{}, "", option);
String groupId = group.getGroupId();
Log.e(TAG, "groupId: " + groupId);
} catch (HyphenateException e) {
e.printStackTrace();
}
}
}).start();
}
private void joinGroup() {
gruopname = join_gruopname.getText().toString().trim();
if (TextUtils.isEmpty(gruopname)) {
showToast("群聊的id不能为空");
return;
}
new Thread(new Runnable() {
@Override
public void run() {
try {
//如果群开群是自由加入的,即group.isMembersOnly()为false,直接join
EMClient.getInstance().groupManager().joinGroup(gruopname);//需异步处理
//需要申请和验证才能加入的,即group.isMembersOnly()为true,调用下面方法
// EMClient.getInstance().groupManager().applyJoinToGroup(gruopname, "求加入");//需异步处理
} catch (HyphenateException e) {
e.printStackTrace();
}
}
}).start();
}
private void submit() {
final String msg = et_msg.getText().toString().trim();
if (TextUtils.isEmpty(msg)) {
showToast("内容不能为空");
return;
}
// TODO validate success, do something
new Thread(new Runnable() {
@Override
public void run() {
//创建一条文本消息,content为消息文字内容,toChatUsername为对方用户或者群聊的id,后文皆是如此
EMMessage message = EMMessage.createTxtSendMessage(msg, gruopname);
//如果是群聊,设置chattype,默认是单聊
message.setChatType(EMMessage.ChatType.GroupChat);
//发送消息
EMClient.getInstance().chatManager().sendMessage(message);
addAdapterList(message);
}
}).start();
// 让编辑框清空
et_msg.setText("");
}
// 把聊天内容发送到Recyclerview上显示
private void addAdapterList(EMMessage message) {
recyclerviewList.add(message);
runOnUiThread(new Runnable() {
@Override
public void run() {
myChatAdapter.notifyDataSetChanged();
// Recyclerview 一直显示最后一条信息
recyclerview.scrollToPosition(recyclerviewList.size() - 1);
}
});
}
private void startVoice() {
AudioUtil.startRecord(new AudioUtil.ResultCallBack() {
@Override
public void onSuccess(String path, long time) {
mPath = path;
mDuration = time;
}
@Override
public void onFail(String msg) {
showToast("录音失败");
}
});
}
private void sendVoice() {
if (mPath.isEmpty()){
showToast("没有");
}
new Thread(new Runnable() {
@Override
public void run() {
//filePath为语音文件路径,length为录音时间(秒)
EMMessage message = EMMessage.createVoiceSendMessage(mPath, (int) mDuration, gruopname);
//如果是群聊,设置chattype,默认是单聊
message.setChatType(EMMessage.ChatType.GroupChat);
EMClient.getInstance().chatManager().sendMessage(message);
addAdapterList(message);
}
}).start();
}
private void showToast(final String msg) {
runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtil.showShort(msg);
}
});
}
private void receiveMsg() {
//记得在不需要的时候移除listener,如在activity的onDestroy()时
EMClient.getInstance().chatManager().addMessageListener(msgListener);
}
// 通过注册消息监听来接收消息
EMMessageListener msgListener = new EMMessageListener() {
@Override
public void onMessageReceived(List<EMMessage> messages) {
//收到消息
if (messages != null && messages.size() > 0) {
final ArrayList<EMMessage> list = new ArrayList<>();
for (EMMessage msg : messages) {
String to = msg.getTo();
Log.e(TAG, "onMessageReceived: " + to);
if (gruopname.equals(to)) {
list.add(msg);
}
}
runOnUiThread(new Runnable() {
@Override
public void run() {
recyclerviewList.addAll(list);
myChatAdapter.notifyDataSetChanged();
recyclerview.scrollToPosition(recyclerviewList.size() - 1);
}
});
}
}
@Override
public void onCmdMessageReceived(List<EMMessage> messages) {
//收到透传消息
}
@Override
public void onMessageRead(List<EMMessage> messages) {
//收到已读回执
}
@Override
public void onMessageDelivered(List<EMMessage> message) {
//收到已送达回执
}
@Override
public void onMessageRecalled(List<EMMessage> messages) {
//消息被撤回
}
@Override
public void onMessageChanged(EMMessage message, Object change) {
//消息状态变动
}
};
@Override
protected void onDestroy() {
super.onDestroy();
EMClient.getInstance().chatManager().removeMessageListener(msgListener);
}
}
网友评论