pdlivexp/OneToOne/src/main/java/com/shayu/onetoone/bean/MessageChatTipsContent.java
2023-10-05 18:29:45 +08:00

124 lines
3.7 KiB
Java

package com.shayu.onetoone.bean;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.NonNull;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import io.rong.common.ParcelUtils;
import io.rong.imlib.MessageTag;
import io.rong.imlib.model.MessageContent;
@MessageTag(value = "MessageChatTipsContent", flag = MessageTag.ISPERSISTED)
public class MessageChatTipsContent extends MessageContent implements Parcelable {
private String content;
private MessageChatTipsContent() {
}
public MessageChatTipsContent(byte[] data) {
if (data == null) {
return;
}
String jsonStr = null;
try {
jsonStr = new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
if (jsonStr == null) {
return;
}
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// 消息携带用户信息时, 自定义消息需添加下面代码
if (jsonObj.has("user")) {
setUserInfo(parseJsonToUserInfo(jsonObj.getJSONObject("user")));
}
// 用于群组聊天, 消息携带 @ 人信息时, 自定义消息需添加下面代码
if (jsonObj.has("mentionedInfo")) {
setMentionedInfo(parseJsonToMentionInfo(jsonObj.getJSONObject("mentionedInfo")));
}
// 将所有自定义变量从收到的 json 解析并赋值
if (jsonObj.has("content")) {
content = jsonObj.optString("content");
}
} catch (JSONException e) {
}
}
public MessageChatTipsContent setContent(String content) {
this.content = content;
return this;
}
public String getContent() {
return content;
}
protected MessageChatTipsContent(Parcel in) {
setExtra(ParcelUtils.readFromParcel(in));
setContent(ParcelUtils.readFromParcel(in));
}
// 快速构建消息对象方法
public static MessageChatTipsContent obtain(String content) {
MessageChatTipsContent msg = new MessageChatTipsContent();
msg.content = content;
return msg;
}
public static final Creator<MessageChatTipsContent> CREATOR = new Creator<MessageChatTipsContent>() {
@Override
public MessageChatTipsContent createFromParcel(Parcel in) {
return new MessageChatTipsContent(in);
}
@Override
public MessageChatTipsContent[] newArray(int size) {
return new MessageChatTipsContent[size];
}
};
@Override
public byte[] encode() {
JSONObject jsonObj = new JSONObject();
try {
// 消息携带用户信息时, 自定义消息需添加下面代码
if (getJSONUserInfo() != null) {
jsonObj.putOpt("user", getJSONUserInfo());
}
// 用于群组聊天, 消息携带 @ 人信息时, 自定义消息需添加下面代码
if (getJsonMentionInfo() != null) {
jsonObj.putOpt("mentionedInfo", getJsonMentionInfo());
}
// 将所有自定义消息的内容,都序列化至 json 对象中
jsonObj.put("content", this.content);
} catch (JSONException e) {
}
try {
return jsonObj.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
}
return null;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
ParcelUtils.writeToParcel(dest, getExtra());
ParcelUtils.writeToParcel(dest, content);
}
}