融雲 聊天的使用
上一篇我們把環境給配置了一下,這一篇就總結下融雲的使用,本工程融雲是在Fragment上靜態整合的,如果想看下其他動態整合或者Activity整合請參考官網:http://www.rongcloud.cn/docs/android.html
記得在MyApplication中註冊一下,並在清單檔案中宣告一下你的MyApplication;
public class MyApplication extends Application{
@Override
public void onCreate() {
super.onCreate();
RongIM.init(this ); //註冊一下
}
}
服務端獲取融雲token,依賴大家可以在這裡下載
有兩個jar包,和一堆檔案,如何獲取token呢?程式碼如下:
public class TookenDaoImp {
public String getToken(String phone, String pass) {
String key = "n19jmcy5996g9"; //融雲的App Key
String secret = "eAHCCbDtzXdfN"; //融雲的App Secret
User user=null;
SdkHttpResult result = null ;
// 獲取token
try {
result = ApiHttpClient.getToken(key, secret, phone, pass,
FormatType.json);
Gson gson=new Gson();
user=gson.fromJson(result.getResult(), User.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user.getUser_token();
}
}
通過註冊時,註冊密碼和手機號(或者使用者主鍵ID),為了方便就直接用手機號了。
case "mima":
String sphone2 = new String(request.getParameter("phone").getBytes("ISO-8859-1"), "UTF-8");
String password2 = new String(request.getParameter("password").getBytes("ISO-8859-1"), "UTF-8");
//通過手機號、密碼 獲取token
TookenDaoImp tookenDaoImp=new TookenDaoImp();
String tooken=tookenDaoImp.getToken(sphone2, password2);
AdoptDaoImp adoptDaoImp9 = new AdoptDaoImp();
//寫入資料庫(方法就不寫了)
p1 = adoptDaoImp9.getAdopt9(sphone2, password2,tooken);
主Activity中就要獲取連線融雲伺服器
//註冊登入後,請求資料庫,可以拿到當前登入使用者物件(一定要把token也拿到,物件可以放在MyApplication裡面,連線服務最好放在登入的Activity中,不要放在主Activity當中,後果可能會連不上融雲伺服器)
String token=((MyApplication)getApplication()).getUser().getUser_token();
//連線融雲伺服器
RongIM.connect(token, new RongIMClient.ConnectCallback() {
@Override
public void onTokenIncorrect() {
}
@Override
public void onSuccess(String s) {
Log.e("success", "success" + s);
}
@Override
public void onError(RongIMClient.ErrorCode errorCode) {
Log.e("success", "success" + errorCode.getValue());
}
});
接著就是自定義的訊息列表:
package com.example.administrator.myapplication14.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.administrator.myapplication14.R;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imlib.model.Conversation;
/**
* @author BULUSILI
* @描述 訊息--私信
* @專案名稱 寵物圈
* @包名 com.example.administrator.myapplication14.be
* @未知 2016-8-9 09:20
*/
public class MessageFragment extends Fragment {
View v;
public MessageFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v=inflater.inflate(R.layout.fragment_message,null);
//這段話不能少,靜態整合,否則會話列表不會顯示內容
ConversationListFragment fragment = (ConversationListFragment) getChildFragmentManager()
.findFragmentById(R.id.conversation_list);
Uri uri = Uri.parse("rong://" + getActivity().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();
fragment.setUri(uri);
return v;
}
}
佈局檔案中
<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"
tools:context="com.example.administrator.myapplication14.Fragment.Fragment4"> //自己的包名
<fragment
android:id="@+id/conversation_list"
android:name="io.rong.imkit.fragment.ConversationListFragment" //這句話就這麼些,不要動
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_below="@+id/button4"
android:layout_gravity="bottom"/>
</RelativeLayout>
自定義的會話介面
package com.example.administrator.myapplication14.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.administrator.myapplication14.R;
public class ConversationActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);
}
}
其佈局檔案:
<?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.example.administrator.myapplication14.Activity.ConversationActivity">
<fragment
android:id="@+id/conversation"
android:name="io.rong.imkit.fragment.ConversationFragment" //還是不要動
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="bottom" />
</RelativeLayout>
會話基本完成,可以用融雲中你的工程的除錯,給註冊token的使用者發訊息了
今天就來優化下介面:會話列表頭像顯示不出來,還有名稱也沒顯示出來,接下來就進行優化:
首先要在會話介面ConversationActivity中設定個toolbar的title
title = getIntent().getData().getQueryParameter("title");
if (title != null && !title.isEmpty()) {
mToolbar.setTitle(title);
} else {
mToolbar.setTitle("null");
}
這個title就是從兩個人聊天那裡傳過來的,大家可以查下RongIM.getInstance().startPrivateChat()的三個引數
1、上下文 2、使用者ID或者手機號只要型別一樣就行 3、最後引數 就是我們傳過去的title。
RongIM.getInstance().startPrivateChat(mContext, mList.get(i).getUser2().getUser_phone() + "", mList.get(i).getUser2().getUser_name());
融云為我們提供了一個資訊提供者,實現implements RongIM.UserInfoProvider介面中的方法,其中引數String s就是你申請的ID或者手機號。
@Override
public UserInfo getUserInfo(String s) {
for (User u : list1) {
/* Log.e("ww3c", "getUserInfo: "+u.getUser_name());
Log.e("ww3c", "getUserInfo2: "+u.getUser_pic());*/
if (u.getUser_phone().equals(s)) {
if (u.getUser_pic() != null) {
return new UserInfo(u.getUser_phone(), u.getUser_name(), Uri.parse(u.getUser_pic()));
}else{
return new UserInfo(u.getUser_phone(),u.getUser_name(),Uri.parse(""));
}
}
}
return null;
}
這樣就差不多了(但是後來發現自己給別人聊天這邊頭像都加載出來了,可是接收聊天使用者那邊頭像,名稱都沒有加載出來),你可以一開始就把你的好友在登入的時候就載入進來,新增到list1這個集合當中。可是我的這個專案,是私信,就是任何人都可以聊天,所以就不可能把所有人的資訊都載入進來,真是絞盡腦汁,耗了好些天。今天看了融雲的API文件,它還有第二種方法,就是點選聊天按鈕的時候,順便把使用者的資訊也傳過去,這樣的思路就可以解決這個BUG了。
關鍵的兩句程式碼如下:
RongIM.getInstance().setCurrentUserInfo(new UserInfo(mList.get(i).getUser2().getUser_phone(),mList.get(i).getUser2().getUser_name()
,Uri.parse(mList.get(i).getUser2().getUser_pic())));
RongIM.getInstance().setMessageAttachedUserInfo(true);
這就是思路,我就把這個完整版的程式碼發下:
package com.example.administrator.myapplication14.Adapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.administrator.myapplication14.Activity.PersonCenterActivity;
import com.example.administrator.myapplication14.MyApplication;
import com.example.administrator.myapplication14.R;
import com.example.administrator.myapplication14.be.Fans;
import com.example.administrator.myapplication14.be.User;
import org.xutils.common.Callback;
import org.xutils.image.ImageOptions;
import org.xutils.x;
import java.util.ArrayList;
import java.util.List;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;
/**
* @author BULUSILI
* @描述 粉絲、關注介面卡
* @專案名稱
* @包名 com.example.administrator.myapplication14.Adapter
* @2016/8/10--19:21
*/
public class MyFansAdapter extends BaseAdapter implements RongIM.UserInfoProvider {
List<Fans> mList;
Context mContext;
ImageOptions mImageOptions;
List<User> list1;
public MyFansAdapter(Context context, List<Fans> list) {
mContext = context;
mList = list;
mImageOptions = new ImageOptions.Builder().setLoadingDrawableId(R.drawable.load2)
.setFailureDrawableId(R.drawable.load_fail).setCircular(true).build();
RongIM.setUserInfoProvider(this, true);//這句話不要忘了
list1=new ArrayList<>();
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int i) {
return mList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
ViewHolder mHolder;
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.fansandfollow, null);
mHolder = new ViewHolder();
mHolder.pic = (ImageView) view.findViewById(R.id.main_fans_tou_xiang);
mHolder.nameTv = (TextView) view.findViewById(R.id.main_fans_name);
mHolder.raceTv = (TextView) view.findViewById(R.id.main_fans_pet);
mHolder.addressTv = (TextView) view.findViewById(R.id.main_fans_address);
mHolder.but = (Button) view.findViewById(R.id.main_fans_but);
view.setTag(mHolder);
} else {
mHolder = (ViewHolder) view.getTag();
}
//載入圖片
x.image().bind(mHolder.pic, mList.get(i).getUser2().getUser_pic(), mImageOptions,
new Callback.CommonCallback<Drawable>() {
@Override
public void onSuccess(Drawable result) {
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
});
mHolder.nameTv.setText(mList.get(i).getUser2().getUser_name());
mHolder.raceTv.setText(mList.get(i).getUser2().getPet_race());
mHolder.addressTv.setText(mList.get(i).getUser2().getAddress());
//頭像跳轉個人詳情頁面
mHolder.pic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(mContext, PersonCenterActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("id", mList.get(i).getUser2().getUser_id());
intent.putExtras(bundle);
mContext.startActivity(intent);
}
});
/* Log.e("ww3c", "getView: "+MyApplication.getUser().getUser_phone());
Log.e("ww3c", "getView: "+MyApplication.getUser().getUser_name() );
Log.e("ww3c", "getView: "+MyApplication.getUser().getUser_pic() );
Log.e("ww3c", "getView: "+mList.get(i).getUser2().getUser_phone() );*/
//私聊就把兩個使用者新增到集合當中
list1.add(new User(MyApplication.getUser().getUser_phone(),MyApplication.getUser().getUser_name(),MyApplication.getUser().getUser_pic(),0));
list1.add(new User(mList.get(i).getUser2().getUser_phone(),mList.get(i).getUser2().getUser_name(),mList.get(i).getUser2().getUser_pic(),
mList.get(i).getUser2().getUser_id()));
//進入聊天介面
mHolder.but.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (RongIM.getInstance() != null) {
RongIM.getInstance().setCurrentUserInfo(new UserInfo(mList.get(i).getUser2().getUser_phone(),mList.get(i).getUser2().getUser_name()
,Uri.parse(mList.get(i).getUser2().getUser_pic())));
RongIM.getInstance().setMessageAttachedUserInfo(true);
RongIM.getInstance().startPrivateChat(mContext, mList.get(i).getUser2().getUser_phone() + "", mList.get(i).getUser2().getUser_name());
}
}
});
return view;
}
@Override
public UserInfo getUserInfo(String s) {
for (User u : list1) {
/* Log.e("ww3c", "getUserInfo: "+u.getUser_name());
Log.e("ww3c", "getUserInfo2: "+u.getUser_pic());*/
if (u.getUser_phone().equals(s)) {
if (u.getUser_pic() != null) {
return new UserInfo(u.getUser_phone(), u.getUser_name(), Uri.parse(u.getUser_pic()));
}else{
return new UserInfo(u.getUser_phone(),u.getUser_name(),Uri.parse(""));
}
}
}
return null;
}
class ViewHolder {
ImageView pic; //頭像
TextView nameTv; //名稱
TextView addressTv;
TextView raceTv;
Button but; //聊天按鈕
}
}