网易云通信实现最简单的单人聊天

首先按照官网进行配置,在build.gradle中添加以下代码:

sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }

清单文件中的AppID替换为在官网注册的应用id

重写Application类(记得在清单文件中引用)

package lipengfei.xunxin;

import android.app.Application;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Environment;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.uinfo.UserInfoProvider;
import com.netease.nimlib.sdk.uinfo.model.UserInfo;

/**
 * Created by Administrator on 2017/12/15.
 */

public class MyApp extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        NIMClient.init(this, loginInfo(), options());

    }
    private SDKOptions options() {
        SDKOptions options = new SDKOptions();

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

        // 配置保存图片,文件,log 等数据的目录
        // 如果 options 中没有设置这个值,SDK 会使用下面代码示例中的位置作为 SDK 的数据目录。
        // 该目录目前包含 log, file, image, audio, video, thumb 这6个目录。
        // 如果第三方 APP 需要缓存清理功能, 清理这个目录下面个子目录的内容即可。
        String sdkPath = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/nim";
        options.sdkStorageRootPath = sdkPath;

        // 配置是否需要预下载附件缩略图,默认为 true
        options.preloadAttach = true;

        // 配置附件缩略图的尺寸大小。表示向服务器请求缩略图文件的大小
        // 该值一般应根据屏幕尺寸来确定, 默认值为 Screen.width / 2
        options.thumbnailSize = 480 / 2;

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


            public int getDefaultIconResId() {
                return R.mipmap.ic_launcher;
            }


            public Bitmap getTeamIcon(String tid) {
                return null;
            }


            public Bitmap getAvatarForMessageNotifier(String account) {
                return null;
            }

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

            @Override
            public Bitmap getAvatarForMessageNotifier(SessionTypeEnum sessionTypeEnum, String s) {
                return null;
            }
        };
        return options;
    }
    // 如果已经存在用户登录信息,返回LoginInfo,否则返回null即可
    private LoginInfo loginInfo() {
        return null;
    }


}

到这里,基本的配置就做完了,然后就是登录,账号和密码可以在官网注册

package lipengfei.xunxin;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.et_id)
    EditText etId;
    @BindView(R.id.et_pass)
    EditText etPass;
    @BindView(R.id.btn1)
    Button btn1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.btn1)
    public void onViewClicked() {
        LoginInfo info=new LoginInfo(etId.getText().toString(),etPass.getText().toString());
        RequestCallback callback=new RequestCallback() {
            @Override
            public void onSuccess(LoginInfo loginInfo) {
                Toast.makeText(MainActivity.this, "登录成功!!!", Toast.LENGTH_SHORT).show();
                //跳转到聊天界面
                startActivity(new Intent(MainActivity.this,Main2Activity.class));
                finish();
            }

            @Override
            public void onFailed(int i) {
                Toast.makeText(MainActivity.this, "登录失败!!!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onException(Throwable throwable) {

            }
        };
        NIMClient.getService(AuthService.class).login(info).setCallback(callback);
    }
}

聊天界面(比较简陋)

package lipengfei.xunxin;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Main2Activity extends AppCompatActivity {
    private String account="z000002";
    private Observer> observer;
    @BindView(R.id.tv_recivetv_in)
    TextView tvRecivetvIn;
    @BindView(R.id.tv_send_out)
    TextView tvSendOut;
    @BindView(R.id.et_input)
    EditText etInput;
    @BindView(R.id.btn_select_people)
    Button btnSelectPeople;
    @BindView(R.id.btn_send)
    Button btnSend;
    @BindView(R.id.btn_out)
    Button btnOut;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ButterKnife.bind(this);
        //注册消息观察者
        registerObserver();
    }
    //别人发的消息在这里监听
    private void registerObserver() {
        observer = new Observer>() {

            @Override
            public void onEvent(List imMessages) {
                IMMessage message = imMessages.get(0);
                //获取聊天的内容
                String content = message.getContent();
                //获取发消息人的昵称
                String nick = message.getFromNick();
                tvRecivetvIn.setText(nick+"--->"+content);
                account=message.getFromAccount();
            }
        };
        //注册
        NIMClient.getService(MsgServiceObserve.class)
                .observeReceiveMessage(observer,true);
    }

    @OnClick({R.id.btn_select_people, R.id.btn_send, R.id.btn_out})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_select_people://选择联系人

                break;
            case R.id.btn_send://发送按钮
                sendMessage();
                break;
            case R.id.btn_out://退出登录
                loginOut();
                break;
        }
    }

    private void loginOut() {
        NIMClient.getService(AuthService.class).logout();
        finish();
        startActivity(new Intent(Main2Activity.this,MainActivity.class));
    }
    //发送消息
    private void sendMessage() {
        String text=etInput.getText().toString();
        IMMessage imMessage= MessageBuilder.createTextMessage(account, SessionTypeEnum.P2P,text);
        NIMClient.getService(MsgService.class).sendMessage(imMessage,false);
        tvSendOut.setText(text);
        etInput.setText("");
    }
    //注销
    @Override
    protected void onDestroy() {
        super.onDestroy();
        NIMClient.getService(MsgServiceObserve.class)
                .observeReceiveMessage(observer,false);
    }
}

你可能感兴趣的:(网易云通信实现最简单的单人聊天)