融云官方文档
下载最新IMKit包,分别导入IMKit(界面库)和IMLib(通讯库),在app的build.gradle中添加:
compile project(':IMKit')
添加融云的APP_ KEY,添加到IMLib的AndroidManifest.xml 的value值下
data
android:name="RONG_CLOUD_APP_KEY"
android:value="您的应用 AppKey" />
在AndroidManifest.xml添加app需要的相关权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
添加7.0的provider配置:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.eeesys.dtwjw_patient.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/rc_file_path" />
provider>
// 如果项目已经有相关7.0权限xml文件,
// 直接加入<external-path name="rc_external_path" path="."/>lu路径即可
6.0需要的权限申请:
private static String[] PERMISSIONS = new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA
};
融云官网
注:使用融云推送功能前必须在“融云开发者后台 - 应用标识”中设置了 Android 应用包名,否则无法接收推送消息。
复制pushLib的so包到libs文件下,适配7.0还需要导入libsqlite.so,详情 戳这里
放置 so 的文件夹位置需要和app的build.gradle 文件中配置的 jni 目录一致
sourceSets {
main {
jni.srcDirs = []
jniLibs.srcDirs = ['libs']
}
}
自定义一个 BroadcastReceiver 类用于接受推送消息:
public class XXReceiver extends PushMessageReceiver {
/* push 通知到达事件*/
@Override
public boolean onNotificationMessageArrived(Context context, PushNotificationMessage message) {
Log.e(Chat , "onNotificationMessageArrived" + GsonTool.toJson(message));
return false; // 返回 false, 会弹出融云 SDK 默认通知; 返回 true, 融云 SDK 不会弹通知, 通知需要由您自定义。
}
/* push 通知点击事件 */
@Override
public boolean onNotificationMessageClicked(Context context, PushNotificationMessage message) {
Log.e(Chat , "onNotificationMessageClicked" + GsonTool.toJson(message));
return false; // 返回 false, 会走融云 SDK 默认处理逻辑, 即点击该通知会打开会话列表或会话界面; 返回 true, 则由您自定义处理逻辑。
}
}
在AndroidManifest.xml文件下注册推送接收器:
<receiver
android:name="您自定义的 broadcastReceiver 类名"
android:exported="true">
<intent-filter>
<action android:name="io.rong.push.intent.MESSAGE_ARRIVED" />
<action android:name="io.rong.push.intent.MI_MESSAGE_ARRIVED" />
<action android:name="io.rong.push.intent.MESSAGE_CLICKED" />
<action android:name="io.rong.push.intent.MI_MESSAGE_CLICKED" />
intent-filter>
receiver>
点击集成小米华为等第三方推送
/**
* 初始化融云
*/
private void initRongYun() {
if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {
// 小米推送,必须在init()方法前
RongPushClient.registerMiPush(this, "2882303761517516557", "5761751652557");
RongIM.setServerInfo("nav.cn.ronghub.com", "up.qbox.me");
// 初始化
RongIM.init(this);
// 设置聊天相关监听
AppContext.init(this);
// 连接融云服务器
RongYUtils.connect(this);
}
}
/**
* 获取当前进程名
* @param context
* @return
*/
public static String getCurProcessName(Context context) {
int pid = android.os.Process.myPid();
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess.processName;
}
}
return null;
}
public class AppContext implements
RongIM.OnSendMessageListener,
RongIMClient.ConnectionStatusListener,
RongIM.UserInfoProvider,
RongIM.GroupInfoProvider {
private static AppContext mRongCloudInstance;
private Context mContext;
public static final String Chat = "chat";
private static DisplayImageOptions options;
/**
* 初始化 RongCloud.
*
* @param context 上下文。
*/
public static void init(Context context) {
if (mRongCloudInstance == null) {
synchronized (AppContext.class) {
if (mRongCloudInstance == null) {
mRongCloudInstance = new AppContext(context);
}
}
}
}
public AppContext(Context mContext) {
this.mContext = mContext;
// 融云用户管理相关
RongyunUserInfoManager.init(mContext);
// 初始化相关监听
initListener();
// 初始化图片加载方式
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.de_default_portrait)
.showImageOnFail(R.drawable.de_default_portrait)
.showImageOnLoading(R.drawable.de_default_portrait)
.displayer(new FadeInBitmapDisplayer(300))
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
}
public static DisplayImageOptions getOptions() {
return options;
}
/**
* init 后就能设置的监听
*/
private void initListener() {
// 显示新消息提醒
RongIM.getInstance().enableNewComingMessageIcon(true);
// 显示未读消息数目
RongIM.getInstance().enableUnreadMessageIcon(true);
// 连接状态
RongIMClient.setConnectionStatusListener(this);
// 发送消息监听
RongIM.getInstance().setSendMessageListener(this);
// 用户提供者
RongIM.setUserInfoProvider(this, true);
// 群组提供者
RongIM.setGroupInfoProvider(this, true);
// 会话消息相关
setInputProvide();
}
/**
* 注册自定义的 ExtensionModule
*/
private void setInputProvide() {
// 接受消息监听
RongIM.setOnReceiveMessageListener(new MyReceiveMessageListener());
List moduleList = RongExtensionManager.getInstance().getExtensionModules();
IExtensionModule defaultModule = null;
if (moduleList != null) {
for (IExtensionModule module : moduleList) {
if (module instanceof DefaultExtensionModule) {
defaultModule = module;
break;
}
}
if (defaultModule != null) {
// 取消默认ExtensionModule
RongExtensionManager.getInstance().unregisterExtensionModule(defaultModule);
// 自定义插件
RongExtensionManager.getInstance().registerExtensionModule(new ExtensionModule());
}
}
}
@Override
public Group getGroupInfo(String s) {
return null;
}
private class MyReceiveMessageListener implements RongIMClient.OnReceiveMessageListener {
/**
* 收到消息的处理。
*
* @param message 收到的消息实体。
* @param left 剩余未拉取消息数目。
* @return 收到消息是否处理完成,true 表示自己处理铃声和后台通知,false 走融云默认处理方式。
*/
@Override
public boolean onReceived(Message message, int left) {
//开发者根据自己需求自行处理
Log.e(Chat, "onReceived" + GsonTool.toJson(message));
Log.e(Chat, "onReceived" + left);
MessageContent messageContent = message.getContent();
// 小灰条消息类型是InformationNotificationMessage,其他一些类型需要自定义
if (messageContent instanceof InformationNotificationMessage) {
InformationNotificationMessage notificationMessage = (InformationNotificationMessage) messageContent;
Log.e(Chat, "onReceived" + GsonTool.toJson(notificationMessage.getExtra()));
Friend friend = GsonTool.fromJson(notificationMessage.getExtra(), Friend.class);
if (friend != null) {
friend.setId(friend.getUser_id());
ChatDbUtils.saveFriend(friend);
// 通知好友列表界面和添加好友界面,有新的好友加入
EventBus.getDefault().post(new AgreeEvent());
Log.e(Chat, "onReceived 开始保存" + GsonTool.toJson(notificationMessage.getExtra()));
}
}
return false;
}
}
@Override
public UserInfo getUserInfo(String s) {
ChatDbUtils.getFriend(s).subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Friend friend) {
UserInfo userInfo = new UserInfo(friend.getId(), friend.getDisplayName(), Uri.parse(friend.getAvatarUrl()));
// 刷新本地用户数据
RongIM.getInstance().refreshUserInfoCache(userInfo);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
return null;
}
@Override
public void onChanged(RongIMClient.ConnectionStatusListener.ConnectionStatus connectionStatus) {
switch (connectionStatus) {
//连接成功。
case CONNECTED:
break;
//断开连接
case DISCONNECTED:
break;
//连接中
case CONNECTING:
break;
//网络不可用。
case NETWORK_UNAVAILABLE:
break;
//用户账户在其他设备登录,本机会被踢掉线
case KICKED_OFFLINE_BY_OTHER_CLIENT:
Intent loginActivityIntent = new Intent();
loginActivityIntent.setClass(mContext, MainActivity.class);
loginActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
loginActivityIntent.putExtra(Constant.EXTRA_RONG_OFFLINE, true);
UserStateUtils.logout(mContext);
mContext.startActivity(loginActivityIntent);
break;
}
}
@Override
public Message onSend(Message message) {
MessageContent messageContent = message.getContent();
// 文本消息
if (messageContent instanceof TextMessage) {
TextMessage textMessage = (TextMessage) messageContent;
LogUtil.e(Chat + "onSend" + textMessage.getContent());
}
return message;
}
@Override
public boolean onSent(Message message, RongIM.SentMessageErrorCode sentMessageErrorCode) {
MessageContent messageContent = message.getContent();
//文本消息
if (messageContent instanceof TextMessage) {
TextMessage textMessage = (TextMessage) messageContent;
LogUtil.e(Chat + "onSent" + textMessage.getContent());
}
return false;
}
}
public class RongyunUserInfoManager {
/**
* 数据库操作对象
*/
static DbManager dbManager = DbUtil.getDbManager();
private final Context mContext;
private static RongyunUserInfoManager sInstance;
public static RongyunUserInfoManager getInstance() {
return sInstance;
}
public static void init(Context context) {
sInstance = new RongyunUserInfoManager(context);
}
public RongyunUserInfoManager(Context context) {
mContext = context;
}
/**
* 获取用户头像,如果头像为空则截取名字来显示
*/
public String getPortraitUri(UserInfo userInfo) {
if (userInfo != null) {
if (userInfo.getPortraitUri() != null) {
if (TextUtils.isEmpty(userInfo.getPortraitUri().toString())) {
if (userInfo.getName() != null) {
return RongGenerate.generateDefaultAvatar(userInfo);
} else {
return "";
}
} else {
return userInfo.getPortraitUri().toString();
}
} else {
if (userInfo.getName() != null) {
return RongGenerate.generateDefaultAvatar(userInfo);
} else {
return "";
}
}
}
return "";
}
/**
* 批量保存好友信息
* @param expertBeans
*/
public void saveFriends(final List expertBeans) {
Log.e("ddddd", "dddddd");
Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter emitter) throws Exception {
dbManager.delete(Friend.class);
dbManager.save(expertBeans);
emitter.onNext("saveFriends" + GsonTool.toJson(expertBeans));
}
}).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String msg) {
Log.e(Chat, msg);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
/**
* 保存或更新单个好友信息
* @param friend
*/
public void saveFriend(final Friend friend) {
Log.e("ddddd", "dddddd");
Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter emitter) throws Exception {
dbManager.saveOrUpdate(friend);
emitter.onNext("saveFriend" + GsonTool.toJson(friend));
}
}).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String msg) {
Log.e(Chat, msg);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
/**
* 获取好友列表
* @return
*/
public Observable> getAllFriends() {
return Observable.create(new ObservableOnSubscribe>() {
@Override
public void subscribe(ObservableEmitter> emitter) throws Exception {
List list = dbManager.findAll(Friend.class);
if (list == null) {
list = new ArrayList<>();
}
Log.e(Chat, "getFriends" + GsonTool.toJson(list));
emitter.onNext(list);
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
/**
* 获取单个好友
* @return
*/
public Observable getFriend(final String expId) {
return Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter emitter) throws Exception {
Friend expertBean = dbManager.selector(Friend.class).where("id", "=", expId).findFirst();
if (expertBean != null) {
emitter.onNext(expertBean);
}
Log.e(Chat, "getFriend" + GsonTool.toJson(expertBean));
}
}).subscribeOn(Schedulers.io()).observeOn(Schedulers.io());
}
/**
* 删除单个好友
* @param id
*/
public void deleteFriend(final String id) {
Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter emitter) throws Exception {
dbManager.delete(Friend.class, WhereBuilder.b("id", "=", id));
emitter.onNext(id);
}
}).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String s) {
Log.e(Chat, "delete"+s);
// 删除会话列表
// RongIMClient.getInstance().removeConversation(Conversation.ConversationType.PRIVATE, id, new RongIMClient.ResultCallback() {
// @Override
// public void onSuccess(Boolean aBoolean) {
// Log.e(Chat, "移除成功");
// }
//
// @Override
// public void onError(RongIMClient.ErrorCode errorCode) {
// Log.e(Chat, "移除失败");
// }
// });
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
/**
* 删除所有好友
*/
public void deleteAllFriends() {
Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter emitter) throws Exception {
dbManager.delete(Friend.class);
emitter.onNext("删除成功");
}
}).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String s) {
Log.e(Chat, s);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
生成文字头像:
注意:SAVEADDRESS 的地址要改成自己应用包名
public class RongGenerate {
private static String SAVEADDRESS = "/data/data/com.eeesys.dtwjw_patient/temp";
private static final String SCHEMA = "file://";
public static String generateDefaultAvatar(String username, String userid) {
String s = null;
if (!TextUtils.isEmpty(username)) {
s = String.valueOf(username.charAt(0));
}
if (s == null) {
s = "A";
}
String color = getColorRGB(userid);
String string = getAllFirstLetter(username);
createDir(SAVEADDRESS);
File f = new File(SAVEADDRESS, string + "_" + userid);
if (f.exists()) {
return SCHEMA + f.getPath();
}
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(220);
paint.setAntiAlias(true);
int width = 480;
int height = 480;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.parseColor(color));
Rect rect = new Rect();
paint.getTextBounds(s, 0, s.length(), rect);
Paint.FontMetrics fm = paint.getFontMetrics();
int textLeft = (int) ((width - paint.measureText(s)) / 2);
int textTop = (int) (height - width / 2 + Math.abs(fm.ascent) / 2 - 25);
canvas.drawText(s, textLeft, textTop, paint);
return saveBitmap(bitmap, string + "_" + userid);
}
public static String generateDefaultAvatar(UserInfo userInfo) {
if (userInfo == null) {
return null;
} else {
return generateDefaultAvatar(userInfo.getName(), userInfo.getUserId());
}
}
private static void createDir(String saveaddress) {
boolean b;
String status = Environment.getExternalStorageState();
b = status.equals(Environment.MEDIA_MOUNTED);
if (b) {
File destDir = new File(saveaddress);
if (!destDir.exists()) {
destDir.mkdirs();
}
}
}
private static String saveBitmap(Bitmap bm, String imageUrlName) {
File f = new File(SAVEADDRESS, imageUrlName);
try {
FileOutputStream out = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Log.e("saveBitmap", "saveBitmap");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return SCHEMA + f.getPath();
}
private static String getColorRGB(String userId) {
String[] portraitColors = {"#e97ffb", "#00b8d4", "#82b2ff", "#f3db73", "#f0857c"};
if (TextUtils.isEmpty(userId)) {
return portraitColors[0];
}
int i = getAscii(userId.charAt(0)) % 5;
return portraitColors[i];
}
private static int getAscii(char cn) {
byte[] bytes = (String.valueOf(cn)).getBytes();
if (bytes.length == 1) { //单字节字符
return bytes[0];
} else if (bytes.length == 2) { //双字节字符
int hightByte = 256 + bytes[0];
int lowByte = 256 + bytes[1];
int ascii = (256 * hightByte + lowByte) - 256 * 256;
return ascii;
} else {
return 0; //错误
}
}
/**
* 生成 view 的截图
*
* @param view
* @return
*/
public static Bitmap takeScreenShot(View view) {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
return view.getDrawingCache();
}
private final static int[] li_SecPosValue = {1601, 1637, 1833, 2078, 2274,
2302, 2433, 2594, 2787, 3106, 3212, 3472, 3635, 3722, 3730, 3858,
4027, 4086, 4390, 4558, 4684, 4925, 5249, 5590
};
private final static String[] lc_FirstLetter = {"a", "b", "c", "d", "e",
"f", "g", "h", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "w", "x", "y", "z"
};
/**
* 取得给定汉字串的首字母串,即声母串
*
* @param str 给定汉字串
* @return 声母串
*/
private static String getAllFirstLetter(String str) {
if (str == null || str.trim().length() == 0) {
return "";
}
String _str = "";
for (int i = 0; i < str.length(); i++) {
_str = _str + getFirstLetter(str.substring(i, i + 1));
}
return _str;
}
/**
* 取得给定汉字的首字母,即声母
*
* @param chinese 给定的汉字
* @return 给定汉字的声母
*/
private static String getFirstLetter(String chinese) {
if (chinese == null || chinese.trim().length() == 0) {
return "";
}
chinese = conversionStr(chinese, "GB2312", "ISO8859-1");
if (chinese.length() > 1) // 判断是不是汉字
{
int li_SectorCode = (int) chinese.charAt(0); // 汉字区码
int li_PositionCode = (int) chinese.charAt(1); // 汉字位码
li_SectorCode = li_SectorCode - 160;
li_PositionCode = li_PositionCode - 160;
int li_SecPosCode = li_SectorCode * 100 + li_PositionCode; // 汉字区位码
if (li_SecPosCode > 1600 && li_SecPosCode < 5590) {
for (int i = 0; i < 23; i++) {
if (li_SecPosCode >= li_SecPosValue[i]
&& li_SecPosCode < li_SecPosValue[i + 1]) {
chinese = lc_FirstLetter[i];
break;
}
}
} else // 非汉字字符,如图形符号或ASCII码
{
chinese = conversionStr(chinese, "ISO8859-1", "GB2312");
chinese = chinese.substring(0, 1);
}
}
return chinese;
}
/**
* 字符串编码转换
*
* @param str 要转换编码的字符串
* @param charsetName 原来的编码
* @param toCharsetName 转换后的编码
* @return 经过编码转换后的字符串
*/
private static String conversionStr(String str, String charsetName, String toCharsetName) {
try {
str = new String(str.getBytes(charsetName), toCharsetName);
} catch (UnsupportedEncodingException ex) {
System.out.println("字符串编码转换异常:" + ex.getMessage());
}
return str;
}
private static String generateRandomCharacter() {
final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
final int length = alphabet.length();
Random random = new Random();
String randomChar = String.valueOf(alphabet.charAt(random.nextInt(length)));
return randomChar;
}
}
Friend表单:
@Table(name = "Friend")
public class Friend implements Serializable, Parcelable {
// 请求添加好友
public static final String REQUEST = "1";
// 拒绝好友请求
public static final String REFUSE = "0";
/**
* 好友融云 id
*/
@Column(name = "id", isId = true)
private String id;
/**
* 好友user id
*/
@Column(name = "user_id")
@SerializedName("friends_id")
private String user_id;
/**
* 姓名首字母
*/
@Column(name = "letters")
private String letters;
/**
* 姓名
*/
@Column(name = "displayName")
@SerializedName("name")
private String displayName;
/**
* 头像
*/
@Column(name = "avatarUrl")
@SerializedName("avatar")
private String avatarUrl;
/**
* 名字拼音
*/
@Column(name = "displayNameSpelling")
private String displayNameSpelling;
/**
* 1:请求;0:拒绝
*/
// @Column(name = "type")
private String type;
public Friend() {
}
public String getType() {
return type == null ? "" : type;
}
public void setType(String type) {
this.type = type;
}
public Friend(String user_id, String displayName, String displayNameSpelling) {
this.user_id = user_id;
this.displayName = displayName;
this.displayNameSpelling = displayNameSpelling;
}
public Friend(String id, String user_id, String displayName, String avatarUrl, String type) {
this.id = id;
this.user_id = user_id;
this.displayName = displayName;
this.avatarUrl = avatarUrl;
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getLetters() {
return letters;
}
public void setLetters(String letters) {
this.letters = letters;
}
public String getDisplayName() {
return displayName == null ? "" : displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getAvatarUrl() {
return avatarUrl == null ? "" : avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public String getDisplayNameSpelling() {
return PinYin.getFullPinYin(displayName);
}
public void setDisplayNameSpelling(String displayNameSpelling) {
this.displayNameSpelling = displayNameSpelling;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeString(this.user_id);
dest.writeString(this.letters);
dest.writeString(this.displayName);
dest.writeString(this.avatarUrl);
dest.writeString(this.displayNameSpelling);
dest.writeString(this.type);
}
protected Friend(Parcel in) {
this.id = in.readString();
this.user_id = in.readString();
this.letters = in.readString();
this.displayName = in.readString();
this.avatarUrl = in.readString();
this.displayNameSpelling = in.readString();
this.type = in.readString();
}
public static final Creator CREATOR = new Creator() {
@Override
public Friend createFromParcel(Parcel source) {
return new Friend(source);
}
@Override
public Friend[] newArray(int size) {
return new Friend[size];
}
};
}
public class ExtensionModule extends DefaultExtensionModule {
@Override
public List getPluginModules(Conversation.ConversationType conversationType) {
// super.getPluginModules(conversationType); 如果需要对红包进行排序可从父类中的 getPluginModules 集合中过滤取出 JrmfExtensionModule
List pluginModuleList = new ArrayList<>();
// 拍照发图片插件
pluginModuleList.add(new ImagePlugin());
// 定位插件
pluginModuleList.add(new DefaultLocationPlugin());
// 语音转文字插件
// pluginModuleList.add(new RecognizePlugin());
return pluginModuleList;
}
@Override
public List getEmoticonTabs() {
return super.getEmoticonTabs();
}
}
public class RongYUtils {
// public static final String TOKEN = "6FrjCo4P2orOd0mgp1Ld4o05peHrFWFfl45oIIHlGgvM4fSoa7fx/M7CX37uLx6flsKT1zxseemcZy1lF3gTyw==";
// public static final String TOKEN = "TtZZoDHRtMMJtxq0KN1/1OCUphKsx76kAraS7I10kYYSN50XvP3YIsvEpEMbc9EK75QuQLkLqAg=";
// 记录token过期重新请求计数值
private static int num = 0;
public static void connect(final Context context, final String token) {
RongIMClient.connect(token, new RongIMClient.ConnectCallback() {
@Override
public void onTokenIncorrect() {
Log.e("onTokenIncorrect", Chat + "token过期");
if (num < 4) {
getToken(context);
}
num++;
}
@Override
public void onSuccess(String userid) {
num = 0;
Log.e("onSuccess", Chat + userid);
}
@Override
public void onError(RongIMClient.ErrorCode errorCode) {
Log.e("onError", Chat + errorCode.getMessage());
}
});
}
/**
* 连接融云服务器
*
* @param context
*/
public static void connect(Context context) {
// 在用户登录情况下
if (UserSpUtil.isLogin(context)) {
String token = (String) SPUtils.get(context, Constant.RONGYUN_TOKEN, "");
if (!TextUtils.isEmpty(token)) {
connect(context, token);
} else {
getToken(context);
}
}
}
/**
* 从Server获取融云token
*
* @param context
*/
public static void getToken(final Context context) {
Param param = new Param(Constant.RONGYUN_GET_TOKEN);
param.addRequestParams("uid", UserSpUtil.getUId(context)); // user id
param.addRequestParams("user_id", UserSpUtil.getUId(context)); // 融云id
param.setIsShowLoading(false);
TxHttp.httpRequest(context, param, new HttpErrorBack() {
@Override
public void err(Throwable ex, boolean isOnCallback, boolean isNetErr) {
}
@Override
public void success(HttpJsonResult httpJsonResult) {
RongYToken token = httpJsonResult.getObject("data", RongYToken.class);
SPUtils.put(context, Constant.RONGYUN_TOKEN, token.getAccess_token());
connect(context, token.getAccess_token());
}
@Override
public void error(HttpJsonResult httpJsonResult) {
}
});
}
/**
* 退出登录的处理
* @param context
*/
public static void logout(Context context){
SPUtils.put(context, Constant.RONGYUN_TOKEN, "");
ChatDbUtils.deleteFriends();
RongIM.getInstance().disconnect();
}
}