安卓 基于云信IM实现登录 + 添加好友 + 单人聊天 功能

#开发前准备
首先注册一个开发者账号,再创建自己的app,自动生成app对应的appkey,去app管理界面创建调试账号
#正文
##配置
创建好项目后,对项目进行配置,官网的帮助文档已经详细说明
##Application类

// An highlighted block
public void onCreate() {
        super.onCreate();
        // ... your codes

        // SDK初始化(启动后台服务,若已经存在用户登录信息, SDK 将完成自动登录)
        NIMClient.init(this, loginInfo(), options());

        // ... your codes
        if (NIMUtil.isMainProcess(this)) {
            // 注意:以下操作必须在主进程中进行
            // 1、UI相关初始化操作
            // 2、相关Service调用
        }
    }

    // 如果返回值为 null,则全部使用默认参数。
    private SDKOptions options() {
        SDKOptions options = new SDKOptions();

        // 如果将新消息通知提醒托管给 SDK 完成,需要添加以下配置。否则无需设置。
        StatusBarNotificationConfig config = new StatusBarNotificationConfig();
        config.notificationEntrance = MainActivity.class; // 点击通知栏跳转到该Activity
        config.notificationSmallIconId = R.drawable.ic_launcher_background;
        // 呼吸灯配置
        config.ledARGB = Color.GREEN;
        config.ledOnMs = 1000;
        config.ledOffMs = 1500;
        // 通知铃声的uri字符串
        config.notificationSound = "android.resource://com.netease.nim.demo/raw/msg";
        options.statusBarNotificationConfig = config;




        // 用户资料提供者, 目前主要用于提供用户资料,用于新消息通知栏中显示消息来源的头像和昵称
        options.userInfoProvider = new UserInfoProvider() {
            @Override
            public UserInfo getUserInfo(String account) {
                return null;
            }

            @Override
            public String getDisplayNameForMessageNotifier(String account, String sessionId,
                                                           SessionTypeEnum sessionType) {
                return null;
            }

            @Override
            public Bitmap getAvatarForMessageNotifier(SessionTypeEnum sessionType, String sessionId) {
                return null;
            }
        };
        return options;
    }

    // 如果已经存在用户登录信息,返回LoginInfo,否则返回null即可
    private LoginInfo loginInfo() {
        return null;
    }

##登录

// An highlighted block
//登录方法 
doLogin(new LoginInfo(yonghuming,mima));

public void doLogin(final LoginInfo info) {
        RequestCallback<LoginInfo> callback =
                new RequestCallback<LoginInfo>() {
                    @Override
                    public void onSuccess(LoginInfo param) {
                        Log.d("ssss","登录成功");
                        Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(MainActivity.this,FriendListActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onFailed(int code) {
                    }

                    @Override
                    public void onException(Throwable exception) {
                        Log.d("sss","登录失败");
                        Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                    // 可以在此保存LoginInfo到本地,下次启动APP做自动登录用
                };
        NIMClient.getService(AuthService.class).login(info)
                .setCallback(callback);
    }

##好友列表

// An highlighted block
//用云信获得好友集合的列表
friends = NIMClient.getService(FriendService.class).getFriendAccounts();
//arraydapt
        arrayAdapter = new ArrayAdapter<>(FriendListActivity.this, R.layout.support_simple_spinner_dropdown_item, friends);
        //设置适配器
        lis.setAdapter(arrayAdapter);
        //点击事件
        lis.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(FriendListActivity.this,Main2Activity.class);
               intent.putExtra("haha",friends.get(i));
                startActivity(intent);

            }
        });

##添加好友

// An highlighted block
final VerifyType verifyType = VerifyType.DIRECT_ADD; // 发起好友验证请求
                String msg = "好友请求附言";
                NIMClient.getService(FriendService.class).addFriend(new AddFriendData(addname.getText().toString().trim(), verifyType, msg))
                        .setCallback(new RequestCallback<Void>() {
                            @Override
                            public void onSuccess(Void param) {
                                initList();

                                Toast.makeText(FriendListActivity.this, "添加好友成功", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onFailed(int code) {

                            }

                            @Override
                            public void onException(Throwable exception) {

                            }
                        });

##聊天
###聊天用RecyclerView左右多布局,以下是聊天的RecyclerView

// An highlighted block
public class MyRecyclerView extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private ArrayList<EMMessage> list;

    public MyRecyclerView(ArrayList<EMMessage> list) {
        this.list = list;
    }
    @Override
    public int getItemViewType(int position) {
        return list.get(position).type;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        RecyclerView.ViewHolder holder = null;
        //类型为1加载左边
        if(i == 0){
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.left_chat, viewGroup, false);
            holder = new Left(view);
            Log.d("zz","左边");
        }else{
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.right_chat, viewGroup, false);
            holder = new Right(view);
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        if(viewHolder instanceof Left){
            Left left = (Left) viewHolder;
            left.left_zi.setText(list.get(i).message);
            Log.d("zz","内容");
        }else if(viewHolder instanceof Right){
            Right right = (Right) viewHolder;
            right.right_zi.setText(list.get(i).message);
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
    public class Left extends RecyclerView.ViewHolder {
        private TextView left_zi;
        public Left(@NonNull View itemView) {
            super(itemView);
            this.left_zi = itemView.findViewById(R.id.left_zi);
        }
    }
    public class Right extends RecyclerView.ViewHolder {
        private TextView right_zi;
        public Right(@NonNull View itemView) {
            super(itemView);
            this.right_zi = itemView.findViewById(R.id.right_zi);
        }
    }
}

##聊天分为发送消息和接收消息
###发送消息

// An highlighted block
final IMMessage textMessage = MessageBuilder.createTextMessage(zhanghao, SessionTypeEnum.P2P, sendtext.getText().toString().trim());

                //发送
                InvocationFuture<Void> voidInvocationFuture = NIMClient.getService(MsgService.class).sendMessage(textMessage, false);
                Log.d("ssss","发送成功:"+sendtext.getText().toString());
                EMMessage emMessage = new EMMessage();
                emMessage.type = 1;
                emMessage.message = sendtext.getText().toString().trim();
                list.add(emMessage);
                MyRecyclerView myRecyclerView = new MyRecyclerView(list);
                recy.setLayoutManager(new LinearLayoutManager(Main2Activity.this));
                recy.setAdapter(myRecyclerView);

###接收消息

// An highlighted block
//接收消息
        Observer<List<IMMessage>> incomingMessageObserver =
                new Observer<List<IMMessage>>() {
                    @Override
                    public void onEvent(List<IMMessage> messages) {
                        // 处理新收到的消息,为了上传处理方便,SDK 保证参数 messages 全部来自同一个聊天对象。
                            String content = messages.get(0).getContent();
                                Log.d("sss",content);
                                Log.d("sss","接收成功");
                                EMMessage emMessage = new EMMessage();
                                emMessage.type = 0;
                                emMessage.message = content;
                                list.add(emMessage);
                                MyRecyclerView myRecyclerView = new MyRecyclerView(list);
                                recy.setLayoutManager(new LinearLayoutManager(Main2Activity.this));
                                recy.setAdapter(myRecyclerView);


                    }
                };
        NIMClient.getService(MsgServiceObserve.class)
                .observeReceiveMessage(incomingMessageObserver, true);

你可能感兴趣的:(安卓 基于云信IM实现登录 + 添加好友 + 单人聊天 功能)