文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

安卓android+WebSocket实现简易QQ聊天室

2022-06-06 13:43

关注

本篇仅介绍实现聊天室的前端,也就是安卓端代码,后端的实现看链接说明

链接说明

1.后端使用了spring boot 框架,若不熟悉,有关spring boot 入门教程请戳此链接使用Intellij IDEA开发第一个spring boot项目
2.websocket后端实现细节戳此链接spring boot练习–利用websocket实现QQ聊天室

界面展示 说明

有两个界面,第一个是登陆界面,我借用了我之前实现的登陆界面,并做了一些微调。需要输入ID和名字,测试的时候输入的ID不能重复,第二个是名字用于界面展示,登陆后跳转入第二个界面,就可以在聊天室里聊天了。

下面图模拟了一组场景,大青儿先进入聊天室,然后小明进入,互相发一段消息后,小明退出聊天室。

大青儿界面变化

以及添加这行,注意添加的位置的区别


第三步具体功能代码 LoginActivity.java
public class LoginActivity extends Activity {
    private EditText mEditTextName,mEditTextId;
    private Button mButtonLogin;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
        mButtonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userName = mEditTextName.getText().toString();
                String userId = mEditTextId.getText().toString();
                User user = new User(userId,userName);
                Intent intent = ChatActivity.newIntent(LoginActivity.this,user.toString());
                startActivity(intent);
                LoginActivity.this.finish();
            }
        });
    }
    private void init(){
        mEditTextName = findViewById(R.id.nickname_editText);
        mEditTextId = findViewById(R.id.id_editText);
        mEditTextName.setCompoundDrawables(initDrawable(R.drawable.nickname),null,null,null);
        mEditTextId.setCompoundDrawables(initDrawable(R.drawable.id),null,null,null);
        mButtonLogin = findViewById(R.id.login);
    }
    
    private Drawable initDrawable(int res){
        Drawable drawable = getResources().getDrawable(res);
        //距离左边距离,距离上边距离,长,宽
        drawable.setBounds(0,0,100,100);
        return drawable;
    }
}
activity_login.xml

    
    
ChatActivity.java
public class ChatActivity extends Activity {
    private ArrayList mUserArrayList = new ArrayList();//定义一个存储信息的列表
    private EditText mInputText;//输入框
    private Button mSend;//发送按钮
    private RecyclerView mRecyclerView;//滑动框
    private UserAdapter mAdapter;//适配器
    private boolean backFlag = false;
    private WebSocket mSocket;
    private User mUser;;//全局User
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        initView();
        String data = getIntent().getStringExtra("data");
        if (!data.equals("")){
            mUser = JSON.parseObject(data,User.class);
        }else {
            mUser = new User("0001","测试名字",R.drawable.boy);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new UserAdapter(mUserArrayList);
        mRecyclerView.setAdapter(mAdapter);
        //开启连接
        start(mUser.getUserId());
        mSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = mInputText.getText().toString();
                if (!"".equals(content)) {
                    Msg msg = new Msg(true,content,false);
                    User tempUser = new User(mUser.getUserId(),mUser.getUserName(),R.drawable.boy,msg);
                    mSocket.send(tempUser.toString());
                    mUserArrayList.add(tempUser);
                    updateRecyclerView();//刷新RecyclerView
                    //清空输入栏
                    mInputText.setText("");
                }
            }
        });
    }
    
    private void updateRecyclerView(){
        //当有新消息时,刷新RecyclerView中的显示
        mAdapter.notifyItemInserted(mUserArrayList.size() - 1);
        //将RecyclerView定位到最后一行
        mRecyclerView.scrollToPosition(mUserArrayList.size() - 1);
    }
    
    private void start(String userId) {
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(300, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(300, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(300, TimeUnit.SECONDS)//设置连接超时时间
                .build();
        //定义request
        Request request = new Request.Builder().url("ws://192.168.5.10:8080/test/"+userId).build();
        //绑定回调接口
        mOkHttpClient.newWebSocket(request, new EchoWebSocketListener());
        mOkHttpClient.dispatcher().executorService().shutdown();
    }
    
    private void output(final User user) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mUserArrayList.add(user);
                updateRecyclerView();
            }
        });
    }
    
    private void initView(){
        mInputText = findViewById(R.id.input_text);
        mSend = findViewById(R.id.send);
        mRecyclerView = findViewById(R.id.msg_recycler_view);
    }
    
    public static Intent newIntent(Context context,String data){
        Intent intent = new Intent(context,ChatActivity.class);
        intent.putExtra("data",data);
        return intent;
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
        if(keyCode==KeyEvent.KEYCODE_BACK&&!backFlag){
            Toast.makeText(ChatActivity.this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
            backFlag = true;
            return true;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }
    
    private final class EchoWebSocketListener extends WebSocketListener {
        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            super.onOpen(webSocket, response);
            mSocket = webSocket;    //实例化web socket
            User user = new User();
            user.setUserMsg(new Msg(false,"连接成功",true));
            output(user);
        }
        @Override
        public void onMessage(WebSocket webSocket, String text) {
            super.onMessage(webSocket, text);
            User user = JSON.parseObject(text, User.class);
            output(user);
        }
        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            super.onClosed(webSocket, code, reason);
            User user = new User();
            user.setUserMsg(new Msg(false,"关闭连接",true));
            output(user);
        }
        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            super.onFailure(webSocket, t, response);
            User user = new User();
            user.setUserMsg(new Msg(false,"连接失败:"+t.getMessage(),true));
            output(user);
        }
    }
}
activity_chat.xml

        
Msg.java
public class Msg {
    private boolean send;//是否是发送的消息
    private String content;//发送的内容
    private boolean system;//是否是系统消息
    public Msg(boolean send, String content) {
        this.send = send;
        this.content = content;
        this.system = false;
    }
    public Msg() {
    }
    public Msg(boolean send, String content, boolean system) {
        this.send = send;
        this.content = content;
        this.system = system;
    }
    public boolean isSystem() {
        return system;
    }
    public void setSystem(boolean system) {
        this.system = system;
    }
    public boolean isSend() {
        return send;
    }
    public void setSend(boolean send) {
        this.send = send;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
User.java
public class User {
    private String userId;
    private String userName;
    private int userImg;
    private Msg userMsg;
    public int getUserImg() {
        return userImg;
    }
    public void setUserImg(int userImg) {
        this.userImg = userImg;
    }
    public User(String userId, String userName, int userImg) {
        this.userId = userId;
        this.userName = userName;
        this.userImg = userImg;
    }
    public User() {
    }
    public User(String userId, String userName) {
        this.userId = userId;
        this.userName = userName;
    }
    public User(String userId, String userName, Msg userMsg) {
        this.userId = userId;
        this.userName = userName;
        this.userMsg = userMsg;
    }
    public User(String userId, String userName, int userImg, Msg userMsg) {
        this.userId = userId;
        this.userName = userName;
        this.userImg = userImg;
        this.userMsg = userMsg;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public Msg getUserMsg() {
        return userMsg;
    }
    public void setUserMsg(Msg userMsg) {
        this.userMsg = userMsg;
    }
    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
UserAdapter.java
public class UserAdapter extends RecyclerView.Adapter{
    private ArrayList mUsers;
    public UserAdapter(ArrayList users) {
        mUsers = users;
    }
    @NonNull
    @Override
    public UserAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.user_item,parent,false);
        return new ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(@NonNull UserAdapter.ViewHolder holder, int position) {
        User user = mUsers.get(position);
        if (user.getUserMsg().isSystem()){//系统消息
            holder.mLinearLayoutSystem.setVisibility(View.VISIBLE);
            holder.mRelativeLayoutReceive.setVisibility(View.GONE);
            holder.mRelativeLayoutSend.setVisibility(View.GONE);
            holder.mTextViewSystemText.setText(user.getUserMsg().getContent());
        }else{
            if (user.getUserMsg().isSend()){//是发送消息
                holder.mLinearLayoutSystem.setVisibility(View.GONE);
                holder.mRelativeLayoutReceive.setVisibility(View.GONE);
                holder.mRelativeLayoutSend.setVisibility(View.VISIBLE);
                holder.mImageViewSend.setImageResource(user.getUserImg());
                holder.mTextViewNameSend.setText(user.getUserName());
                holder.mTextViewContentSend.setText(user.getUserMsg().getContent());
            }else { //接收的消息
                holder.mLinearLayoutSystem.setVisibility(View.GONE);
                holder.mRelativeLayoutReceive.setVisibility(View.VISIBLE);
                holder.mRelativeLayoutSend.setVisibility(View.GONE);
                holder.mImageViewReceive.setImageResource(user.getUserImg());
                holder.mTextViewNameReceive.setText(user.getUserName());
                holder.mTextViewContentReceive.setText(user.getUserMsg().getContent());
            }
        }
    }
    @Override
    public int getItemCount() {
        return mUsers.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder {
        //绑定所有视图
        RelativeLayout mRelativeLayoutSend,mRelativeLayoutReceive;
        LinearLayout mLinearLayoutSystem;
        ImageView mImageViewReceive,mImageViewSend;
        TextView mTextViewNameReceive,mTextViewNameSend,mTextViewContentReceive,mTextViewContentSend,mTextViewSystemText;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            mRelativeLayoutReceive = itemView.findViewById(R.id.receive_relative);
            mRelativeLayoutSend = itemView.findViewById(R.id.send_relative);
            mLinearLayoutSystem = itemView.findViewById(R.id.system_layout);
            mImageViewReceive = itemView.findViewById(R.id.image_receive);
            mImageViewSend = itemView.findViewById(R.id.image_send);
            mTextViewNameReceive = itemView.findViewById(R.id.text_name_receive);
            mTextViewNameSend = itemView.findViewById(R.id.text_name_send);
            mTextViewContentReceive = itemView.findViewById(R.id.text_content_receive);
            mTextViewContentSend = itemView.findViewById(R.id.text_content_send);
            mTextViewSystemText = itemView.findViewById(R.id.system_text);
        }
    }
}
user_item.xml

图片资源

应用中大部分图片资源都是只起装饰性作用,可以在阿里巴巴矢量图标库获取,当然包裹聊天文字的图片是.9格式图片,可以参考:Android Studio制作.9图片

提醒一哈

先配置好后端再进行前端测试,不然没连上服务器会报错并闪退。因为当你点发送的时候,有一段代码中websocket并没有被实例化。


作者:大青儿


阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-移动开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯