Android--使用融云SDK开发即时聊天(二)----设置单聊

来源:互联网 发布:mac 代理服务器软件 编辑:程序博客网 时间:2024/07/17 03:39

转载请注明出处:http://blog.csdn.net/skyunicorn/article/details/50906199,谢谢

上一次我们做了一个连接测试,测试显示连接成功,这次我们做一个单聊测试。

一、新建一个javabean,命名为Friend

有三个String字段,分别为userId,name,portraitUri;

分别生成其getter和setter还有构造方法(AS快捷键为ALT+Insert)。

 

二、重新配置MainActivity

因为我们的这次目的是开发一个单聊模式,实现2个用户的聊天,所以我们在此设定死2个用户,分别10010和10086。

.xml文件配置如下

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.demo.dell.testchatdemo1.MainActivity">    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="10dp"        android:hint="请输入用户名..." />    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="10dp"        android:hint="请输入密码..." />    <Button        android:id="@+id/connect_10010"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="20dp"        android:text="点击连接融云server(用户1)" />    <Button        android:id="@+id/connect_10086"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="20dp"        android:text="点击连接融云server(用户2)" /></LinearLayout>


.class文件

package com.demo.dell.testchatdemo1;import android.app.Activity;import android.content.Intent;import android.net.Uri;import android.support.annotation.MainThread;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.Toast;import java.util.ArrayList;import java.util.List;import io.rong.imkit.RongIM;import io.rong.imlib.RongIMClient;import io.rong.imlib.model.UserInfo;public class MainActivity extends Activity implements View.OnClickListener, RongIM.UserInfoProvider {    private static final String token1 = "uFHTGcZMzSCSugxRmRA7lRf1AH3ArXbvLbNoacl+xLf5jFwBPsU0d+uBXWEKpLMlrv/cTWb4cdSdzE0shl1/oA==";    private static final String token2 = "0L3LhZvmEhmeY/O6z+jqkDdw425PLr6tFkyLhkSfXOmlDCw9tNfLfUcyTHdC9vWaTz2z6Hb0nwEYYnzkBXdBuw==";    private List<Friend> userIdList;    private static final String TAG = "MainActivity";    private Button mUser1, mUser2;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mUser1 = (Button) findViewById(R.id.connect_10010);        mUser2 = (Button) findViewById(R.id.connect_10086);        mUser1.setOnClickListener(this);        mUser2.setOnClickListener(this);        initUserInfo();    }    private void connectRongServer(String token) {        RongIM.connect(token, new RongIMClient.ConnectCallback() {            @Override            public void onSuccess(String userId) {                if (userId.equals("10010")) {                    mUser1.setText("用户1连接服务器成功");                    startActivity(new Intent(MainActivity.this, HomeActivity.class));                    Toast.makeText(MainActivity.this, "connect server success 10010", Toast.LENGTH_SHORT).show();                } else {                    startActivity(new Intent(MainActivity.this, HomeActivity.class));                    Toast.makeText(MainActivity.this, "connect server success 10086", Toast.LENGTH_SHORT).show();                }            }            @Override            public void onError(RongIMClient.ErrorCode errorCode) {                // Log.e("onError", "onError userid:" + errorCode.getValue());//获取错误的错误码                Log.e(TAG, "connect failure errorCode is : " + errorCode.getValue());            }            @Override            public void onTokenIncorrect() {                Log.e(TAG, "token is error ,please check token and appkey");            }        });    }    @Override    public void onClick(View v) {        if (v.getId() == R.id.connect_10010) {            connectRongServer(token1);        } else if (v.getId() == R.id.connect_10086) {            connectRongServer(token2);        }    }    private void initUserInfo() {        userIdList = new ArrayList<Friend>();        userIdList.add(new Friend("10010", "联通", "http://www.51zxw.net/bbs/UploadFile/2013-4/201341122335711220.jpg"));//联通图标        userIdList.add(new Friend("10086", "移动", "http://img02.tooopen.com/Download/2010/5/22/20100522103223994012.jpg"));//移动图标        RongIM.setUserInfoProvider(this, true);    }    @Override    public UserInfo getUserInfo(String s) {        for (Friend i : userIdList) {            if (i.getUserId().equals(s)) {                Log.e(TAG, i.getPortraitUri());                return new UserInfo(i.getUserId(), i.getName(), Uri.parse(i.getPortraitUri()));            }        }        Log.e("MainActivity", "UserId is : " + s);        return null;    }}

三、配置登录后的主页

在这里我们的主页是用ViewPager+Fragment显示的

activity_home.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.demo.dell.testchatdemo1.HomeActivity">    <android.support.v4.view.ViewPager        android:id="@+id/viewpager"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1" /></LinearLayout>


HomeActivity.class

package com.demo.dell.testchatdemo1;import android.net.Uri;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentPagerAdapter;import android.support.v4.view.ViewPager;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import java.util.ArrayList;import java.util.List;import io.rong.imkit.fragment.ConversationListFragment;import io.rong.imlib.model.Conversation;public class HomeActivity extends FragmentActivity {    private ViewPager mViewPager;    private FragmentPagerAdapter mFragmentPagerAdapter;//将tab页面持久在内存中    private Fragment mConversationList;    private Fragment mConversationFragment = null;    private List<Fragment> mFragment = new ArrayList<>();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_home);        mConversationList = initConversationList();//获取融云会话列表的对象        mViewPager = (ViewPager) findViewById(R.id.viewpager);        mFragment.add(HomeFragment.getInstance());//加入第一页        mFragment.add(mConversationList);//加入会话列表        mFragment.add(FriendFragment.getInstance());//加入第三页        //配置ViewPager的适配器        mFragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {            @Override            public Fragment getItem(int position) {                return mFragment.get(position);            }            @Override            public int getCount() {                return mFragment.size();            }        };        mViewPager.setAdapter(mFragmentPagerAdapter);    }    private Fragment initConversationList() {        /**         * appendQueryParameter对具体的会话列表做展示         */        if (mConversationFragment == null) {            ConversationListFragment listFragment = ConversationListFragment.getInstance();            Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()                    .appendPath("conversationList")                    .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false")//设置私聊会话是否聚合显示                    .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "true")                    .appendQueryParameter(Conversation.ConversationType.DISCUSSION.getName(), "false")//设置私聊会话是否聚合显示                    .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "false")//设置私聊会是否聚合显示                    .build();            listFragment.setUri(uri);            return listFragment;        } else {            return mConversationFragment;        }    }}


四、配置HomeFragment

 

HomeFragment.class

package com.demo.dell.testchatdemo1;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;/** * Created by DELL on 2016/3/14. */public class HomeFragment extends Fragment {    public static HomeFragment instance = null;//单例模式    public static HomeFragment getInstance() {        if (instance == null) {            instance = new HomeFragment();        }        return instance;    }    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        TextView tv = new TextView(getActivity());        tv.setText("第一页");        return tv;    }}


五、配置FriendFragment

 

friend_fragment.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <Button        android:id="@+id/friend"        android:text="好友XXX"        android:layout_width="match_parent"        android:layout_height="wrap_content" /></LinearLayout>


FriendFragment.class

package com.demo.dell.testchatdemo1;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.TextView;import io.rong.imkit.RongIM;/** * Created by DELL on 2016/3/14. */public class FriendFragment extends Fragment {    public static FriendFragment instance = null;//单例模式    public static FriendFragment getInstance() {        if (instance == null) {            instance = new FriendFragment();        }        return instance;    }    private View mView;    private Button mButton;    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        mView = inflater.inflate(R.layout.friend_fragment,null);        mButton = (Button) mView.findViewById(R.id.friend);        mButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (RongIM.getInstance()!=null){                    RongIM.getInstance().startPrivateChat(getActivity(),"10086","私人聊天");                }            }        });//        TextView tv = new TextView(getActivity());//        tv.setText("第三页");//        return tv;        return mView;    }}




六、配置聊天交互

 

activity_conversation.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.demo.dell.testchatdemo1.ConversationActivity">    <fragment        android:id="@+id/conversation"        android:name="io.rong.imkit.fragment.ConversationFragment"        android:layout_width="match_parent"        android:layout_height="match_parent" /></RelativeLayout>



ConversationActivity.java

不做什么变动



AndroidManifest.xml中

在ConversationActivity的注册文件中添加

<intent-filter>    <action android:name="android.intent.action.VIEW" />    <category android:name="android.intent.category.DEFAULT" />    <data        android:host="com.demo.dell.testchatdemo1"        android:pathPrefix="/conversation/"        android:scheme="rong" /></intent-filter>





DEMO下载地址:http://download.csdn.net/detail/skyunicorn/9475259



1 1
原创粉丝点击