編輯:關於 Android 程式設計
想在聊天裡發小影片?發 GIF?發紅包?發自定義表情?在融雲都能做。而這些看起來五花八門的功能,本質上都是同一件事——傳檔案,副檔名不外乎 .png、.gif、.mp4、.amr。只要把檔案傳輸這條路打通,上面所有需求都能順著衍生出來。
整個機制拆成四塊:
1. 自定義訊息型別。透過融雲的訊息收發通道傳輸自訂的 MessageContent。
2. 自定義 UI 樣式。用融雲的訊息模板(Provider)控制會話頁面的呈現,換成紅包就換一張資源圖即可。
3. 檔案要先能上傳。把本地檔案送到後端或雲端儲存(示例用七牛),取得一組可公開下載的 http/https 路徑。
4. 收到訊息後下載。點擊訊息時取出訊息體裡的 remoteUrl,下載回來後再交給 App 自己的邏輯處理。
也就是說,你只需要一個 upLoadFile 與一個 downLoadFile,其餘都是訊息封裝與 UI 的事。
FileMessage:訊息實體,繼承 MessageContent。
FileMessageProvider:訊息模板,負責會話列表的 UI。
SendFileProvider:發送入口,掛在「+」號的擴充面板裡。
重點是兩個方法:encode() 把物件序列化成 JSON,建構子則負責反序列化。
@MessageTag(value = "RC:FileMsg", flag = MessageTag.ISCOUNTED | MessageTag.ISPERSISTED)
public class FileMessage extends MessageContent {
private Uri mThumUri; // 縮圖
private Uri mLocalUri; // 本地路徑 file:///
private Uri mRemoteUri; // 網路路徑 https://
private boolean mUpLoadExp = false;
private String mBase64;
boolean mIsFull;
protected String extra;
public FileMessage(byte[] data) {
String jsonStr = new String(data);
try {
JSONObject jsonObj = new JSONObject(jsonStr);
if (jsonObj.has("fileUri")) {
String uri = jsonObj.optString("fileUri");
if (!TextUtils.isEmpty(uri)) setRemoteUri(Uri.parse(uri));
if (getRemoteUri() != null && getRemoteUri().getScheme() != null
&& getRemoteUri().getScheme().equals("file")) {
setLocalUri(getRemoteUri());
}
}
if (jsonObj.has("content")) setBase64(jsonObj.optString("content"));
if (jsonObj.has("extra")) setExtra(jsonObj.optString("extra"));
if (jsonObj.has("exp")) setUpLoadExp(true);
if (jsonObj.has("isFull")) setIsFull(jsonObj.optBoolean("isFull"));
if (jsonObj.has("user")) setUserInfo(parseJsonToUserInfo(jsonObj.getJSONObject("user")));
} catch (JSONException e) {
Log.e("JSONException", e.getMessage());
}
}
public static FileMessage obtain(Uri thumUri, Uri localUri) {
return new FileMessage(thumUri, localUri);
}
@Override
public byte[] encode() {
JSONObject jsonObj = new JSONObject();
try {
if (!TextUtils.isEmpty(mBase64)) {
jsonObj.put("content", mBase64);
}
if (mRemoteUri != null) {
jsonObj.put("fileUri", mRemoteUri.toString());
} else if (getLocalUri() != null) {
jsonObj.put("fileUri", getLocalUri().toString());
}
if (mUpLoadExp) jsonObj.put("exp", true);
jsonObj.put("isFull", mIsFull);
if (!TextUtils.isEmpty(getExtra())) jsonObj.put("extra", getExtra());
if (getJSONUserInfo() != null) jsonObj.putOpt("user", getJSONUserInfo());
} catch (JSONException e) {
Log.e("JSONException", e.getMessage());
}
mBase64 = null;
return jsonObj.toString().getBytes();
}
// 因為訊息要在行程之間傳遞,還必須實作 Parcelable
@Override public int describeContents() { return 0; }
public FileMessage(Parcel in) {
setExtra(ParcelUtils.readFromParcel(in));
mLocalUri = ParcelUtils.readFromParcel(in, Uri.class);
mRemoteUri = ParcelUtils.readFromParcel(in, Uri.class);
mThumUri = ParcelUtils.readFromParcel(in, Uri.class);
setUserInfo(ParcelUtils.readFromParcel(in, UserInfo.class));
mIsFull = ParcelUtils.readIntFromParcel(in) == 1;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
ParcelUtils.writeToParcel(dest, getExtra());
ParcelUtils.writeToParcel(dest, mLocalUri);
ParcelUtils.writeToParcel(dest, mRemoteUri);
ParcelUtils.writeToParcel(dest, mThumUri);
ParcelUtils.writeToParcel(dest, getUserInfo());
ParcelUtils.writeToParcel(dest, mIsFull ? 1 : 0);
}
public static final Creator<FileMessage> CREATOR = new Creator<FileMessage>() {
@Override public FileMessage createFromParcel(Parcel source) { return new FileMessage(source); }
@Override public FileMessage[] newArray(int size) { return new FileMessage[size]; }
};
}
這個類主要做兩件事:定義訊息攜帶哪些欄位(本地路徑、網路路徑、縮圖、附加資訊),以及處理序列化與 Parcelable。若要做紅包,就多加一個金額欄位;要做語音,就多一個時長欄位,套路完全相同。
@ProviderTag(messageContent = FileMessage.class, showPortrait = true,
showProgress = true, centerInHorizontal = false)
public class FileMessageProvider extends IContainerItemProvider.MessageProvider<FileMessage> {
@Override
public View newView(Context context, ViewGroup group) {
View view = LayoutInflater.from(context).inflate(R.layout.de_item_file_message, group, false);
ViewHolder holder = new ViewHolder();
holder.message = (TextView) view.findViewById(R.id.rc_msg);
holder.img = (AsyncImageView) view.findViewById(R.id.rc_img);
view.setTag(holder);
return view;
}
@Override
public void bindView(View v, int position, FileMessage content, UIMessage message) {
ViewHolder holder = (ViewHolder) v.getTag();
// 依收發方向換氣泡背景
v.setBackgroundResource(message.getMessageDirection() == Message.MessageDirection.SEND
? io.rong.imkit.R.drawable.rc_ic_bubble_no_right
: io.rong.imkit.R.drawable.rc_ic_bubble_no_left);
holder.img.setResource(content.getThumUri() == null ? null : new Resource(content.getThumUri()));
// 上傳中的進度顯示
int progress = message.getProgress();
if (message.getSentStatus().equals(Message.SentStatus.SENDING) && progress < 100) {
holder.message.setText(progress == 0
? RongContext.getInstance().getResources().getString(io.rong.imkit.R.string.rc_waiting)
: progress + "%");
holder.message.setVisibility(View.VISIBLE);
} else {
holder.message.setVisibility(View.GONE);
}
}
@Override
public Spannable getContentSummary(FileMessage data) {
return new SpannableString(RongContext.getInstance().getResources().getString(R.string.de_plugins_file));
}
@Override public void onItemClick(View view, int position, FileMessage content, UIMessage message) { }
@Override public void onItemLongClick(View view, int position, FileMessage content, UIMessage message) { }
class ViewHolder { AsyncImageView img; TextView message; }
}
這一層只管樣式:換圖片、換氣泡、顯示上傳進度百分比。改成紅包時,把版面配置與圖示換掉就好。
public class SendFileProvider extends InputProvider.ExtendProvider {
private Context context;
public SendFileProvider(RongContext context) {
super(context);
this.context = context;
}
@Override
public Drawable obtainPluginDrawable(Context context) {
return context.getResources().getDrawable(io.rong.imkit.R.drawable.rc_ic_picture);
}
@Override
public CharSequence obtainPluginTitle(Context context) { return "文件"; }
@Override
public void onPluginClick(View view) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("file/*");
startActivityForResult(i, 1);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null) return;
if (!data.getData().getScheme().equals("file")) return;
Uri uri = data.getData();
File file = new File(uri.getPath());
if (!file.exists()) {
Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show();
return;
}
Conversation conversation = getCurrentConversation();
sendFile(conversation.getConversationType(), conversation.getTargetId(), file, uri);
}
private void sendFile(Conversation.ConversationType type, String id, File file, Uri uri) {
if (RongIM.getInstance() == null || RongIM.getInstance().getRongIMClient() == null) return;
// TODO: 這裡才是真正要補上的地方——先把 file 上傳,拿到 remoteUrl 後再塞進 FileMessage
FileMessage fileMessage = FileMessage.obtain(uri, uri);
RongIM.getInstance().getRongIMClient().sendMessage(
Message.obtain(id, conversation -> fileMessage), null, null,
new RongIMClient.SendMessageCallback() {
@Override public void onAttached(Message message) { }
@Override public void onSuccess(Message message) { }
@Override public void onError(Message message, RongIMClient.ErrorCode code) { }
});
}
}
要特別注意:這裡直接開啟系統檔案總管。部分客製化 ROM 的 ACTION_GET_CONTENT 行為有差異,可能挑不到檔案;原生系統、三星與小米的機型大致沒問題。若要穩定,建議自己掃描過濾、做一個簡單的檔案選擇器。
另外原範例是借用 sendImageMessage 來傳檔案,這是取巧做法(沿用圖片訊息的通道),正式專案請改用 sendMessage 搭配自己的上傳流程,並在 onProgress 中回報進度。
1. 在 Application 註冊訊息型別與模板。這步很簡單但極易遺漏,忘了就會出現「訊息收到卻顯示不出來」:
RongIM.registerMessageType(FileMessage.class);
RongIM.registerMessageTemplate(new FileMessageProvider());
2. 點擊訊息時攔下來做下載:
if (message.getContent() instanceof FileMessage) {
FileMessage fileMessage = (FileMessage) message.getContent();
if (message.getMessageDirection().equals(Message.MessageDirection.RECEIVE)) {
Intent intent = new Intent(context, FileActivity.class);
intent.putExtra("photo", fileMessage.getLocalUri() == null
? fileMessage.getRemoteUri() : fileMessage.getLocalUri());
if (fileMessage.getThumUri() != null) {
intent.putExtra("thumbnail", fileMessage.getThumUri());
}
context.startActivity(intent);
}
}
3. 上傳與下載要自己實作。這部分取決於你的後端或雲端儲存服務,不是融雲負責的。常見做法是:本地檔案先上傳取得 URL → 帶著 URL 送出自定義訊息 → 對方點擊時判斷本地有沒有快取,沒有就下載。
把這條鏈路走通之後,小影片、GIF、自定義表情、紅包都只是換個副檔名與 UI 的事。程式碼僅供參考,建議理解後自己動手寫一遍,特別是上傳下載與快取策略,那才是真正需要依業務調整的部分。
Android 自定義控制項入門:Canvas 與 Paint 繪製基礎圖形詳解
前言 上一篇寫自定義 View 已經是大半年前的事了,其間一直想接著寫,但總覺得自己火候不夠,怕誤人子弟。這段時間專案剛收尾,終於有點空檔,於是跟著前輩們的思路,把自定義
Android 學習筆記:Fragment 生命週期與回調順序
Fragment 作為 Android 中常用的界面組件,擁有自己的生命週期。理解 Fragment 的回調順序,有助於開發者在合適的時機保存狀態、恢復數據以及釋放資源。
常用 Android 開發代碼片段大合集(持續更新)
這份清單匯聚了日常開發中反覆用到、卻常常想不起來的 API 與小技巧,來源包括個人積累和社區文章。內容難免有重複或過時之處,看到問題歡迎指正。 一、View 與佈局 s
Material Design 深入學習:定義陰影與裁剪視圖(四)
Material Design 引入了「深度」的概念,讓 UI 元素能透過陰影的高低,幫助使用者理解各元素的相對重要性,並把注意力聚焦在手邊正在進行的工作上。 高程(E