Android聊天软件开发(基于网易云IM即时通讯)——发送文本消息(四)

发送界面

activity_send_message.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="44dp"
            android:orientation="horizontal"
            android:gravity="center_vertical"
            android:background="@color/deepskyblue">

            <LinearLayout
                android:id="@+id/ll_return"
                android:layout_width="44sp"
                android:layout_height="44sp"
                android:gravity="center_vertical"
                >

                <ImageView
                    android:layout_width="24sp"
                    android:layout_height="24sp"
                    android:src="@drawable/return1"
                    android:layout_marginStart="20dp"
                    android:contentDescription="@string/tv_icon_des"
                    />

            </LinearLayout>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btn_send_message"
                android:textColor="@color/white"
                android:textSize="20sp"
                android:layout_marginStart="20dp"
                />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            >

            <EditText
                android:id="@+id/ed_send_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <Button
                android:id="@+id/btn_send_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/btn_send_message" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="消息接收显示" />

            <TextView
                android:id="@+id/tv_receive_message"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>

    </LinearLayout>

    <!--<RelativeLayout-->
        <!--android:id="@+id/rl_loading"-->
        <!--android:layout_width="150dp"-->
        <!--android:layout_height="150dp"-->
        <!--android:layout_gravity="center"-->
        <!--android:background="@drawable/shape_label_clarity_black">-->

        <!--<com.github.ybq.android.spinkit.SpinKitView-->
            <!--xmlns:app="http://schemas.android.com/apk/res-auto"-->
            <!--android:id="@+id/pb_loading"-->
            <!--style="@style/SpinKitView.Large.Circle"-->
            <!--android:layout_width="wrap_content"-->
            <!--android:layout_height="wrap_content"-->
            <!--android:layout_centerInParent="true"-->
            <!--app:SpinKit_Color="@color/white" />-->

        <!--<TextView-->
            <!--android:id="@+id/tv_loading_text"-->
            <!--android:layout_below="@id/pb_loading"-->
            <!--android:layout_centerHorizontal="true"-->
            <!--android:layout_width="wrap_content"-->
            <!--android:layout_height="wrap_content"-->
            <!--android:textColor="@color/white"-->
            <!--/>-->

    <!--</RelativeLayout>-->

</FrameLayout>
SendMessageActivity
package heath.com.chat.message;

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

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import heath.com.chat.R;
import heath.com.chat.service.IMService;
import heath.com.chat.utils.ToastUtil;

public class SendMessageActivity extends AppCompatActivity implements View.OnClickListener {

    private static IMService mImService;
    private LinearLayout mLlReturn;
    private EditText mEdSendText;
    /**
     * 发消息
     */
    private Button mBtnSendText;
    private static TextView mTvReceiveMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_message);
        initView();
        init();
    }

    private void init() {
        // 绑定服务
        Intent service = new Intent(SendMessageActivity.this, IMService.class);
        bindService(service, mMyServiceConnection, BIND_AUTO_CREATE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 解绑服务
        if (mMyServiceConnection != null) {
            unbindService(mMyServiceConnection);
        }
    }

    MyServiceConnection mMyServiceConnection = new MyServiceConnection();

    private void initView() {
        mLlReturn = (LinearLayout) findViewById(R.id.ll_return);
        mEdSendText = (EditText) findViewById(R.id.ed_send_text);
        mBtnSendText = (Button) findViewById(R.id.btn_send_text);
        mBtnSendText.setOnClickListener(this);
        mTvReceiveMessage = (TextView) findViewById(R.id.tv_receive_message);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.ll_return:
                finish();
                break;
            case R.id.btn_send_text:
                final String content = mEdSendText.getText().toString();//消息文本
                String account = "1";//目前这里是写死的账号
                SessionTypeEnum type =  SessionTypeEnum.P2P;//会话类型
                final IMMessage textMessage = MessageBuilder.createTextMessage(account, type, content);
                NIMClient.getService(MsgService.class).sendMessage(textMessage, false).setCallback(new RequestCallback<Void>() {
                    @Override
                    public void onSuccess(Void param) {
                        ToastUtil.toastOnUiThread(SendMessageActivity.this,"发送成功");
                    }

                    @Override
                    public void onFailed(int code) {

                    }

                    @Override
                    public void onException(Throwable exception) {

                    }
                });
                mEdSendText.setText("");
                break;
        }
    }

    public static void updateData(String message){
        mTvReceiveMessage.setText(message);
    }

    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out
                    .println("--------------onServiceConnected--------------");
            IMService.MyBinder binder = (IMService.MyBinder) service;
            mImService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out
                    .println("--------------onServiceDisconnected--------------");

        }
    }

}

接收消息

我这里使用服务来处理消息的接收

IMService
package heath.com.chat.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.google.gson.Gson;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.friend.model.AddFriendNotify;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.SystemMessageObserver;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.constant.SystemMessageType;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.SystemMessage;

import java.util.List;

import heath.com.chat.message.MessageFragment;
import heath.com.chat.message.SendMessageActivity;
import heath.com.chat.utils.ACache;

public class IMService extends Service {

    private static ACache aCache;
    private Gson gson;

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public class MyBinder extends Binder {
        // 返回server的实例
        public IMService getService() {
            return IMService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        aCache = ACache.get(this);
        gson = new Gson();
        NIMClient.getService(SystemMessageObserver.class).observeReceiveSystemMsg(systemMessageObserver, true);
        NIMClient.getService(MsgServiceObserve.class).observeReceiveMessage(incomingMessageObserver, true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NIMClient.getService(SystemMessageObserver.class).observeReceiveSystemMsg(systemMessageObserver, false);
        NIMClient.getService(MsgServiceObserve.class).observeReceiveMessage(incomingMessageObserver, false);
    }

    Observer<SystemMessage> systemMessageObserver = new Observer<SystemMessage>() {
        @Override
        public void onEvent(SystemMessage systemMessage) {
            if (systemMessage.getType() == SystemMessageType.AddFriend) {
                AddFriendNotify attachData = (AddFriendNotify) systemMessage.getAttachObject();
                if (attachData != null) {
                    // 针对不同的事件做处理
                    if (attachData.getEvent() == AddFriendNotify.Event.RECV_ADD_FRIEND_DIRECT) {
                        // 对方直接添加你为好友
                    } else if (attachData.getEvent() == AddFriendNotify.Event.RECV_AGREE_ADD_FRIEND) {
                        // 对方通过了你的好友验证请求
                    } else if (attachData.getEvent() == AddFriendNotify.Event.RECV_REJECT_ADD_FRIEND) {
                        // 对方拒绝了你的好友验证请求
                    } else if (attachData.getEvent() == AddFriendNotify.Event.RECV_ADD_FRIEND_VERIFY_REQUEST) {
                        // 对方请求添加好友,一般场景会让用户选择同意或拒绝对方的好友请求。
                        // 通过message.getContent()获取好友验证请求的附言
                    }
                }
            }
        }
    };
    private Observer<List<IMMessage>> incomingMessageObserver =
            new Observer<List<IMMessage>>() {
                @Override
                public void onEvent(List<IMMessage> messages) {
                    // 处理新收到的消息,为了上传处理方便,SDK 保证参数 messages 全部来自同一个聊天对象。
                    for (IMMessage message : messages) {
                        Log.i("message", "onEvent===========: " + message.getContent());
                        if (message.getMsgType() == MsgTypeEnum.text) {
                            SendMessageActivity.updateData(message.getContent());
                        }
                    }

                }
            };

}

使用了服务,记得在AndroidManifest.xml注册一下

<service android:name=".service.IMService" />

记得在LoginActivity里,登录后启动一下

Intent server = new Intent(LoginActivity.this,
        IMService.class);
startService(server);

项目下载地址:https://download.csdn.net/download/qq_32090185/11122479

猜你喜欢

转载自blog.csdn.net/qq_32090185/article/details/90208355