代码实现的过程中参考了博客上几篇优秀的文章和其中的代码,本想放连接但是找不到了,如果大佬们看见了可以告知我,感谢大佬们。因为各种原因,没有使用网易云信自带的UI库,有兴趣的大佬可以试试,也在开发者文档种。
本文建立在基本网易云信依赖已经部署好的情况下,可详见网易云信官网开发者手册
https://doc.yunxin.163.com/docs/TM5MzM5Njk/TY1OTU4NDQ?platformId=600
也可以参考我上一篇博客
https://blog.csdn.net/qq_45796133/article/details/121236550
先上效果图,对方信息的发送利用的是网易云信自带的API调试台
上代码,首先是SendMessageActivity
package com.example.mycampus;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.mycampus.Adapter.ChatAdapter;
import com.example.mycampus.Utils.IMService;
import com.example.mycampus.bean.PersonChat;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import java.util.ArrayList;
import java.util.List;
public class SendMessageActivity extends AppCompatActivity implements View.OnClickListener {
private static IMService mImService;
private LinearLayout mLlReturn;
EditText et_chat_message;
// private EditText mEdSendText;
// private EditText mPrSendText;
/**
* 发消息
*/
// private Button mBtnSendText;
// private static TextView mTvReceiveMessage;
private static ChatAdapter chatAdapter;
/**
* 声明ListView
*/
private static ListView lv_chat_dialog;
/**
* 集合
*/
// static PersonChat personChat = new PersonChat();
private static List<PersonChat> personChats = new ArrayList<PersonChat>();
private static Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
int what = msg.what;
switch (what) {
case 1:
/**
* ListView条目控制在最后一行
*/
lv_chat_dialog.setSelection(personChats.size());
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_message);
initView();
init();
}
private void init() {
// 绑定服务
Intent service = new Intent(SendMessageActivity.this, IMService.class);
bindService(service, mMyServiceConnection, BIND_AUTO_CREATE);
}
@Override
public void onDestroy() {
super.onDestroy();
// 解绑服务
if (mMyServiceConnection != null) {
unbindService(mMyServiceConnection);
}
}
MyServiceConnection mMyServiceConnection = new MyServiceConnection();
private void initView() {
PersonChat personChat = new PersonChat();
// mLlReturn = (LinearLayout) findViewById(R.id.ll_return);
lv_chat_dialog = (ListView) findViewById(R.id.lv_chat_dialog);
Button btn_chat_message_send = (Button) findViewById(R.id.btn_chat_message_send);
et_chat_message = (EditText) findViewById(R.id.et_chat_message);
/**
*setAdapter
*/
chatAdapter = new ChatAdapter(this, personChats);
lv_chat_dialog.setAdapter(chatAdapter);
btn_chat_message_send.setOnClickListener(this::onClick);
// mEdSendText = (EditText) findViewById(R.id.ed_send_text);
// mBtnSendText = (Button) findViewById(R.id.btn_send_text);
// mPrSendText=(EditText) findViewById(R.id.ed_send_person);
// mBtnSendText.setOnClickListener(this);
// mTvReceiveMessage = (TextView) findViewById(R.id.tv_receive_message);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
default:
break;
// case R.id.ll_return:
// finish();
// break;
case R.id.btn_chat_message_send:
final String content =et_chat_message.getText().toString();//消息文本
String account = "2";//目前这里是写死的账号,可以根据自己的需求改
SessionTypeEnum type = SessionTypeEnum.P2P;//会话类型
final IMMessage textMessage = MessageBuilder.createTextMessage(account, type, content);
NIMClient.getService(MsgService.class).sendMessage(textMessage, false).setCallback(new RequestCallback<Void>() {
@Override
public void onSuccess(Void param) {
Toast.makeText(SendMessageActivity.this, "发送成功~", Toast.LENGTH_SHORT).show();
PersonChat personChat = new PersonChat();
//代表自己发送
personChat.setMeSend(true);
//得到发送内容
personChat.setChatMessage(et_chat_message.getText().toString());
//加入集合
personChats.add(personChat);
//清空输入框
et_chat_message.setText("");
//刷新ListView
chatAdapter.notifyDataSetChanged();
handler.sendEmptyMessage(1);
}
@Override
public void onFailed(int code) {
}
@Override
public void onException(Throwable exception) {
}
});
// mEdSendText.setText("");
break;
}
}
public static void updateData(String message){
System.out.println("更新成功");
//update();
PersonChat personChat = new PersonChat();
//代表自己发送
personChat.setMeSend(false);
//得到发送内容
personChat.setChatMessage(message);
//加入集合
personChats.add(personChat);
//清空输入框
//et_chat_message.setText("");
//刷新ListView
chatAdapter.notifyDataSetChanged();
handler.sendEmptyMessage(1);
// et_.setText(message);
// PersonChat personChat = new PersonChat();
//代表自己发送
// personChat.setMeSend(false);
//得到发送内容
// personChat.setChatMessage(message);
//加入集合
// personChatss.add(personChat);
//清空输入框
// et_chat_message.setText("");
//刷新ListView
// chatAdapter.notifyDataSetChanged();
// handler.sendEmptyMessage(1);
}
class MyServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out
.println("--------------onServiceConnected--------------");
IMService.MyBinder binder = (IMService.MyBinder) service;
mImService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
System.out
.println("--------------onServiceDisconnected--------------");
}
}
}`
然后是IMservice类,用于通信服务
package com.example.mycampus.Utils;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.example.mycampus.SendMessageActivity;
import com.example.mycampus.bean.PersonChat;
import com.google.gson.Gson;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.friend.model.AddFriendNotify;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.SystemMessageObserver;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.constant.SystemMessageType;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.SystemMessage;
import java.util.List;
public class IMService extends Service {
private static ACache aCache;
private Gson gson;
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
public class MyBinder extends Binder {
// 返回server的实例
public IMService getService() {
return IMService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
aCache = ACache.get(this);
gson = new Gson();
// NIMClient.getService(SystemMessageObserver.class).observeReceiveSystemMsg(systemMessageObserver, true);
NIMClient.getService(MsgServiceObserve.class).observeReceiveMessage(incomingMessageObserver, true);
}
@Override
public void onDestroy() {
super.onDestroy();
// NIMClient.getService(SystemMessageObserver.class).observeReceiveSystemMsg(systemMessageObserver, false);
NIMClient.getService(MsgServiceObserve.class).observeReceiveMessage(incomingMessageObserver, false);
}
private Observer<List<IMMessage>> incomingMessageObserver =
new Observer<List<IMMessage>>() {
@Override
public void onEvent(List<IMMessage> messages) {
// 处理新收到的消息,为了上传处理方便,SDK 保证参数 messages 全部来自同一个聊天对象。
for (IMMessage message : messages) {
Log.i("message", "onEvent===========: " + message.getContent());
if (message.getMsgType() == MsgTypeEnum.text) {
SendMessageActivity.updateData(message.getContent());
// personChats.add(personChat);
}
}
}
};
}
然后是适配器ChatAdapter
public class ChatAdapter extends BaseAdapter {
private Context context;
private List<PersonChat> lists;
public ChatAdapter(Context context, List<PersonChat> lists) {
super();
this.context = context;
this.lists = lists;
}
/**
* 是否是自己发送的消息
*
* @author cyf
*
*/
public static interface IMsgViewType {
int IMVT_COM_MSG = 0;// 收到对方的消息
int IMVT_TO_MSG = 1;// 自己发送出去的消息
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return lists.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return lists.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
/**
* 得到Item的类型,是对方发过来的消息,还是自己发送出去的
*/
public int getItemViewType(int position) {
PersonChat entity = lists.get(position);
if (entity.isMeSend()) {// 收到的消息
return IMsgViewType.IMVT_COM_MSG;
} else {// 自己发送的消息
return IMsgViewType.IMVT_TO_MSG;
}
}
@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
HolderView holderView = null;
PersonChat entity = lists.get(arg0);
boolean isMeSend = entity.isMeSend();
if (holderView == null) {
holderView = new HolderView();
if (isMeSend) {
arg1 = View.inflate(context, R.layout.chat_dialog_right_item,
null);
holderView.tv_chat_me_message = (TextView) arg1
.findViewById(R.id.tv_chat_me_message);
holderView.tv_chat_me_message.setText(entity.getChatMessage());
} else {
arg1 = View.inflate(context, R.layout.chat_dialog_left_item,
null);
holderView.tv_name = (TextView) arg1
.findViewById(R.id.tvname);
holderView.tv_name.setText(entity.getChatMessage());
}
arg1.setTag(holderView);
} else {
holderView = (HolderView) arg1.getTag();
}
return arg1;
}
class HolderView {
TextView tv_chat_me_message;
TextView tv_name;
}
@Override
public boolean isEnabled(int position) {
return false;
}
}
接下来是布局文件,左对话框与右对话框
<?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:background="#c2c2c2"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/app_lvjian_rbtn_normal_background"
android:orientation="vertical"
android:padding="8dp" >
<ListView
android:id="@+id/lv_chat_dialog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#0000"
android:dividerHeight="8dp"
android:scrollbars="none" >
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_marginTop="8dp"
android:orientation="horizontal" >
<EditText
android:id="@+id/et_chat_message"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:textSize="14sp"
android:background="@drawable/app_lvjian_rbtn_normal_background"
android:gravity="center|left"
android:padding="8dp" />
<Button
android:id="@+id/btn_chat_message_send"
android:textColor="#fff"
android:text="发送"
android:layout_width="64dp"
android:layout_marginLeft="8dp"
android:layout_height="match_parent"
android:layout_gravity="center|right"
android:layout_marginRight="4dp"
android:background="#EA6A6A" />
</LinearLayout>
</LinearLayout>
<?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="horizontal" >
<TextView
android:id="@+id/tv_chat_me_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:layout_toLeftOf="@+id/iv_chat_imagr_right"
android:background="@drawable/app_lvjian_chat_right"
android:padding="8dp"
android:text="test222" />
<ImageView
android:id="@+id/iv_chat_imagr_right"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_alignParentRight="true"
android:layout_gravity="top"
android:src="@mipmap/person" />
</RelativeLayout>
activity_send_message
<?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:background="#c2c2c2"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/app_lvjian_rbtn_normal_background"
android:orientation="vertical"
android:padding="8dp" >
<ListView
android:id="@+id/lv_chat_dialog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#0000"
android:dividerHeight="8dp"
android:scrollbars="none" >
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_marginTop="8dp"
android:orientation="horizontal" >
<EditText
android:id="@+id/et_chat_message"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:textSize="14sp"
android:background="@drawable/app_lvjian_rbtn_normal_background"
android:gravity="center|left"
android:padding="8dp" />
<Button
android:id="@+id/btn_chat_message_send"
android:textColor="#fff"
android:text="发送"
android:layout_width="64dp"
android:layout_marginLeft="8dp"
android:layout_height="match_parent"
android:layout_gravity="center|right"
android:layout_marginRight="4dp"
android:background="#EA6A6A" />
</LinearLayout>
</LinearLayout>
大功告成,因为代码写了有点久,所以如果有什么问题欢迎提问,错误或者可以改进的地方也欢迎指正!