Android基于云信实现单聊

来源:互联网 发布:淘宝新店铺如何做活 编辑:程序博客网 时间:2024/04/29 23:23

一、添加依赖:

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'

三、清单文件:

<!-- 权限声明 -->
<!-- 访问网络状态 -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- 控制呼吸灯,振动器等,用于新消息提醒 -->
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.VIBRATE" />
<!-- 外置存储存取权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<!-- 多媒体相关 -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<!-- 如果需要实时音视频通话模块,下面的权限也是必须的。否则,可以不加 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />

<!-- SDK 权限申明, 第三方 APP 接入时,请将 com.netease.nim.demo 替换为自己的包名 -->
<!-- 和下面的 uses-permission 一起加入到你的 AndroidManifest 文件中。 -->
<permission
android:name="com.think.easynetim.permission.RECEIVE_MSG"
android:protectionLevel="signature" />

<!-- 接收 SDK 消息广播权限, 第三方 APP 接入时,请将 com.netease.nim.demo 替换为自己的包名 -->
<uses-permission android:name="com.think.easynetim.permission.RECEIVE_MSG" />

<application
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">

<!--
APP key, 可以在这里设置,也可以在 SDKOptions 中提供。
如果 SDKOptions 中提供了,取 SDKOptions 中的值。
-->
<meta-data
android:name="com.netease.nim.appKey"
android:value="c0e2d1ccb1a8d8653dce73a8b07597a5" />

<!-- 声明网易云通信后台服务,如需保持后台推送,使用独立进程效果会更好。 -->
<service
android:name="com.netease.nimlib.service.NimService"
android:process=":core" />

<!-- 运行后台辅助服务 -->
<service
android:name="com.netease.nimlib.service.NimService$Aux"
android:process=":core" />

<!-- 声明网易云通信后台辅助服务 -->
<service
android:name="com.netease.nimlib.job.NIMJobService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"
android:process=":core" />

<!--
网易云通信SDK的监视系统启动和网络变化的广播接收器,用户开机自启动以及网络变化时候重新登录,
保持和 NimService 同一进程
-->
<receiver
android:name="com.netease.nimlib.service.NimReceiver"
android:exported="false"
android:process=":core">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>

<!-- 网易云通信进程间通信 Receiver -->
<receiver android:name="com.netease.nimlib.service.ResponseReceiver" />

<!-- 网易云通信进程间通信service -->
<service android:name="com.netease.nimlib.service.ResponseService" />

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

<!--!!!!!!-->
<!--<provider
android:name="com.netease.nimlib.ipc.NIMContentProvider"
android:authorities="com.think.easynetim.ipc.provider"
android:exported="false"
android:process=":core" />-->

<activity android:name=".MainActivity"
android:theme="@style/Theme.AppCompat.DayNight.NoActionBar"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".WelcomeActivity"></activity>
</application>


四、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<LoginInfo> callback =
                new RequestCallback<LoginInfo>() {
                    @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<List<IMMessage>> 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<List<IMMessage>>() {
            @Override
            public void onEvent(List<IMMessage> 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:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
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">

<TextView
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" />

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

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

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

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

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

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

<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:text="登录!" />

</LinearLayout>
八、Welcome类:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        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" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="收到的消息:" />
        <TextView
            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" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="发出的消息:" />
        <TextView
            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" />
    </LinearLayout>
    <EditText
        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="输入消息..." />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="10dp"
        android:paddingRight="10dp">
        <Button
            android:id="@+id/btn_select_people"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="选择联系人" />
        <Button
            android:id="@+id/btn_send"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="发送" />
        <Button
            android:id="@+id/btn_out"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="退出" />
    </LinearLayout>
</LinearLayout>

原创粉丝点击