Android基于云信实现单聊

一、添加依赖:

library-demonstrate  (由于上传文件限制)

二、添加包:

// 添加依赖。注意,版本号必须一致。
// 基础功能 (必需)
compile 'com.netease.nimlib:basesdk:4.4.0'
// 音视频和互动白板服务需要
compile 'com.netease.nimlib:nrtc:4.4.0'
// 音视频需要
compile 'com.netease.nimlib:avchat:4.4.0'
// 聊天室需要
compile 'com.netease.nimlib:chatroom:4.4.0'
// 互动白板服务需要
compile 'com.netease.nimlib:rts:4.4.0'
// 全文检索服务需要
compile 'com.netease.nimlib:lucene:4.4.0'
implementation 'com.jakewharton:butterknife:8.8.1'
//要添加此依赖否则事件无法响应
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

三、清单文件:


























android:glEsVersion="0x00020000"
android:required="true" />



android:name="com.think.easynetim.permission.RECEIVE_MSG"
android:protectionLevel="signature" />




android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.DayNight.NoActionBar">


android:name="com.netease.nim.appKey"
android:value="c0e2d1ccb1a8d8653dce73a8b07597a5" />


android:name="com.netease.nimlib.service.NimService"
android:process=":core" />


android:name="com.netease.nimlib.service.NimService$Aux"
android:process=":core" />


android:name="com.netease.nimlib.job.NIMJobService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"
android:process=":core" />


android:name="com.netease.nimlib.service.NimReceiver"
android:exported="false"
android:process=":core">












android:name="com.netease.cosine.target"
android:value="" />
android:name="com.netease.cosine.target.receiver"
android:value="com.netease.nimlib.service.NimReceiver" />




android:theme="@style/Theme.AppCompat.DayNight.NoActionBar"
>








四、MyApp类:

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        // SDK初始化(启动后台服务,若已经存在用户登录信息, SDK 将完成自动登录)
        NIMClient.init(this, loginInfo(), options());
    }
    // 如果返回值为 null,则全部使用默认参数。
    private SDKOptions options() {
        SDKOptions options = new SDKOptions();
        // 如果将新消息通知提醒托管给 SDK 完成,需要添加以下配置。否则无需设置。
        StatusBarNotificationConfig config = new StatusBarNotificationConfig();
        config.notificationEntrance = WelcomeActivity.class; // 点击通知栏跳转到该Activity
        config.notificationSmallIconId = R.mipmap.ic_launcher_round;
        // 呼吸灯配置
        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;
            }
            @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;
    }
}

五、Activity类:

public class MainActivity extends AppCompatActivity {
    @BindView(R.id.tv_account)
    EditText tvAccount;
    @BindView(R.id.tv_pw)
    EditText tvPw;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }
    @OnClick(R.id.btn_login)
    public void onViewClicked() {
        //封装登录信息.
        LoginInfo info
                = new LoginInfo(tvAccount.getText().toString(),tvPw.getText().toString());
        //请求服务器的回调
        RequestCallback callback =
                new RequestCallback() {
                    @Override
                    public void onSuccess(LoginInfo param) {
                        DemonstrateUtil
                                .showLogResult("onSuccess--"+param.getAccount()+"--"+param.getToken());
                        DemonstrateUtil.showToastResult(MainActivity.this,"登录成功!");
                        // 可以在此保存LoginInfo到本地,下次启动APP做自动登录用
                        //跳转到消息页面
                        startActivity(new Intent(MainActivity.this,WelcomeActivity.class));
                        finish();
                    }
                    @Override
                    public void onFailed(int code) {
                        DemonstrateUtil.showLogResult("登录失败!返回码"+code);
                    }
                    @Override
                    public void onException(Throwable exception) {
                        DemonstrateUtil.showLogResult(exception.toString());
                    }
                };
        //发送请求.
        NIMClient.getService(AuthService.class).login(info)
                .setCallback(callback);
    }
}

六、Welcome类:
public class WelcomeActivity extends AppCompatActivity {
    @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_send)
    Button btnSend;
    @BindView(R.id.btn_out)
    Button btnOut;
    @BindView(R.id.btn_select_people)
    Button btnSelectPeople;
    private Observer> incomingMessageObserver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcom);
        ButterKnife.bind(this);
        //注册消息观察者,registerObserver
        registerObserver();
    }
    private void registerObserver() {
        // 处理新收到的消息,为了上传处理方便,SDK 保证参数 messages 全部来自同一个聊天对象。
        //消息接收观察者
        incomingMessageObserver = new Observer>() {
            @Override
            public void onEvent(List messages) {
                // 处理新收到的消息,为了上传处理方便,SDK 保证参数 messages 全部来自同一个聊天对象。
                IMMessage imMessage = messages.get(0);
                tvRecivetvIn.setText(imMessage.getFromNick() + "-->:" + imMessage.getContent());
                account = imMessage.getFromAccount();
            }
        };
        //注册消息接收观察者,
        //true,代表注册.false,代表注销
        NIMClient.getService(MsgServiceObserve.class)
                .observeReceiveMessage(incomingMessageObserver, true);
    }
    @OnClick({R.id.btn_send, R.id.btn_out, R.id.btn_select_people})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_send:
                //发送消息
                sendMessage();
                break;
            case R.id.btn_out:
                //退出登录
                loginOut();
                break;
            case R.id.btn_select_people:
                //选择联系人.
                final String[] accounts = {"zxn001", "zxn002", "zxn003", "zxn004", "zxn011"};
                final String[] items = {
                        "吃饭",
                        "睡觉",
                        "敲码",
                        "爱表达",
                        "万万不能打游戏",
                };
                DialogUtil.showListDialog(WelcomeActivity.this, "请选择联系人!", items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        account = accounts[which];
                        DemonstrateUtil.showToastResult(WelcomeActivity.this, items[which]);
                    }
                });
                break;
        }
    }
    private String account = "zxn002";
    private void sendMessage() {
        // 以单聊类型为例
        SessionTypeEnum sessionType = SessionTypeEnum.P2P;
        String text = etInput.getText().toString();
        // 创建一个文本消息
        IMMessage textMessage = MessageBuilder.createTextMessage(account, sessionType, text);
        // 发送给对方
        NIMClient.getService(MsgService.class).sendMessage(textMessage, false);
        tvSendOut.setText(text);
    }
    private void loginOut() {
        NIMClient.getService(AuthService.class).logout();
        finish();
        startActivity(new Intent(this, MainActivity.class));
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销消息接收观察者.
        NIMClient.getService(MsgServiceObserve.class)
                .observeReceiveMessage(incomingMessageObserver, false);
    }
}
七、Activity的xml:
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"
android:orientation="vertical"
tools:context="com.think.easynetim.MainActivity">

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="@android:color/holo_green_light"
android:gravity="center"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:text="登录"
android:textColor="@android:color/white"
android:textSize="20sp" />

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal"
android:paddingLeft="20dp"
android:paddingRight="20dp">

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="帐号:"
android:textColor="@color/colorAccent" />

android:id="@+id/tv_account"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入您的帐号!" />


android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal"
android:paddingLeft="20dp"
android:paddingRight="20dp">

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密码:"
android:textColor="@color/colorAccent" />

android:id="@+id/tv_pw"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入您的帐号!" />


八、Welcome类:
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
            android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="@android:color/holo_green_light"
        android:gravity="center"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:text="单聊"
        android:textColor="@android:color/white"
        android:textSize="20sp" />
            android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp">
                    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="收到的消息:" />
                    android:id="@+id/tv_recivetv_in"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:text="1111"
            android:textColor="@android:color/holo_red_light" />
                    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="发出的消息:" />
                    android:id="@+id/tv_send_out"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:text="2222"
            android:textColor="@android:color/holo_blue_light" />
   
            android:id="@+id/et_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="5dp"
        android:hint="输入消息..." />
            android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="10dp"
        android:paddingRight="10dp">
       
       
       

你可能感兴趣的:(Android基于云信实现单聊)