How does rongyun implement File Sending (advanced)

Source: Internet
Author: User
Tags sendfile

How does rongyun implement File Sending (advanced)
Good luck ~!

Want to publish in chatSmall videos?Gif Animation?Red Packets? SendingCustom expressions? No problem! All functions can be implemented in rongyun! Whether it's a small video, a gif, a red envelope, or a custom expression, it's all about data transmission. the suffix is nothing more. png. gif. mp4. amr and so on, as long as we have mastered all the above requirements for File Sending, it can be achieved based on file message derivation. Let's take a look at the implementation of file messages and the sending and receiving of file messages. Let's Go!

Let's take a look at the effect:

Next, we will share the implementation principles and implementation code with you: you need to customize the message type. You need to use the rongyun message sending and receiving channel UI display. You need to use the rongyun message template to customize the UI display style. You can use the background storage or cloud storage (in this example, qiniu) the uploaded file is given a downloadable public path (for example, http: // xxx & https: // xxx) sending a message is actually uploading a local file (you need a method similar to upLoadFile ), and the upload progress prompt. When a message is received, the user clicks the message and obtains the retomeUrl contained in the message body and downloads the message (you need a method similar to downLoadFile) after downloading the file, you can process it based on your App logic requirements. Implementation Code: FileMessageThis class is a file message entity class inherited from the self-financing cloud MessageContent FileMessageProviderThis is a file message template that displays messages on the ui of the session interface. SendFileProviderThis class is the entry for Sending File messages.
The above are the three most important logic code classes. Let's talk about the purpose first. There are some details of the code. We will keep up with the code and share it in detail later. FileMessage
Package io. rong. message; import android. annotation. suppressLint; import android.net. uri; import android. OS. parcel; import android. text. textUtils; import android. util. log; import org. json. JSONException; import org. json. JSONObject; import io. rong. common. parcelUtils; import io. rong. imlib. messageTag; import io. rong. imlib. model. messageContent; import io. rong. imlib. model. userInfo;/*** Created by Bob on 15/12/24. * /@ SuppressLint ("ParcelCreator") @ MessageTag (value = "RC: FileMsg", flag = MessageTag. ISCOUNTED | MessageTag. ISPERSISTED, messageHandler = FileMessageHandler. class) public class FileMessage extends MessageContent {private Uri mThumUri; private Uri mLocalUri; private Uri mRemoteUri; private boolean mUpLoadExp = false; private String mBase64; boolean mIsFull; protected String extra; /*** get additional message information ** @ Return additional information */public String getExtra () {return extra;}/*** set additional message information ** @ param extra additional information */public void setExtra (String extra) {this. extra = 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 (parseJsonToUs ErInfo (jsonObj. getJSONObject ("user");} catch (JSONException e) {Log. e ("JSONException", e. getMessage () ;}} public FileMessage () {} private FileMessage (Uri thumbUri, Uri localUri) {mThumUri = thumbUri; mLocalUri = localUri;} private FileMessage (Uri thumbUri, uri localUri, boolean original) {mThumUri = thumbUri; mLocalUri = localUri; mIsFull = original;}/*** generates a FileMessage object. **/Public static FileMessage obtain (Uri thumUri, Uri localUri) {return new FileMessage (thumUri, localUri);}/*** generates a FileMessage object. **/Public static FileMessage obtain (Uri thumUri, Uri localUri, boolean isFull) {return new FileMessage (thumUri, localUri, isFull);}/*** generates a FileMessage object. ** @ Return ImageMessage object instance. */Public static FileMessage obtain () {return new FileMessage ();}/*** get the thumbnail Uri. ** @ Return thumbnail Uri (this is an internal Uri when receiving a message. You must use ResourceManager. getInstance (). getFile (new Resource (Uri) to obtain the actual address ). */Public Uri getThumUri () {return mThumUri;}/***** @ return true/false */public boolean isFull () {return mIsFull ;} /*** set the flag of the sent source image. **/Public void setIsFull (boolean isFull) {this. mIsFull = isFull;}/*** sets the thumbnail Uri. ** @ Param thumUri thumbnail address */public void setThumUri (Uri thumUri) {this. mThumUri = thumUri;}/*** get the local image address (file :///). ** @ Return local image address (file :///). */Public Uri getLocalUri () {return mLocalUri;}/*** sets the local image address (file :///). ** @ Param localUri: Local Image address (file :///). */public void setLocalUri (Uri localUri) {this. mLocalUri = localUri;}/*** get the network image address (http ://). ** @ Return network image address (http ://). */Public Uri getRemoteUri () {return mRemoteUri;}/*** sets the network image address (http ://). ** @ Param remoteUri: network image address (http ://). */Public void setRemoteUri (Uri remoteUri) {this. mRemoteUri = remoteUri;}/*** set the Base64 data to be passed ** @ param base64 base64 data. */Public void setBase64 (String base64) {mBase64 = base64;}/*** get the Base64 data to be passed. ** @ Return base64 data. */Public String getBase64 () {return mBase64;}/*** indicates whether the upload fails. ** @ Return indicates whether the upload fails. */Public boolean isUpLoadExp () {return mUpLoadExp;}/*** sets whether the upload fails. ** @ Param upLoadExp: whether the upload fails. */Public void setUpLoadExp (boolean upLoadExp) {this. mUpLoadExp = upLoadExp;} @ Override public byte [] encode () {JSONObject jsonObj = new JSONObject (); try {if (! TextUtils. isEmpty (mBase64) {jsonObj. put ("content", mBase64);} else {Log. d ("ImageMessage", "base64 is null");} 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 () ;}/ *** describes the types of special objects contained in the Parcelable Object arrangement information. ** @ Return indicates the arrangement of special object types of Parcelable objects. */@ Override public int describeContents () {return 0 ;}/ *** constructor. ** @ Param in initializes the input Parcel. */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;}/*** write the class data to the external provided Parcel. ** @ Param dest refers to the Parcel to which the object is written. * @ Param flags the additional flag for how the object is written may be 0 or PARCELABLE_WRITE_RETURN_VALUE. * // @ 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);}/*** read interface, which is used to construct an instance that implements Parcelable from Parcel. */Public static final Creator
  
   
CREATOR = new Creator
   
    
() {@ Override public FileMessage createFromParcel (Parcel source) {return new FileMessage (source) ;}@ Override public FileMessage [] newArray (int size) {return new FileMessage [size] ;}};}
   
  
In the custom message class, the persistent serialization of messages and the content and members of messages are implemented. For example, to upload a file, I must know the local path of the file, for example, to send a red packet message, we need to know the amount of the red packet. FileMessageProvider
Package io. rong. app. message. provider; import android. content. context; import android. text. spannable; import android. text. spannableString; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; import android. widget. textView; import com. sea_monster.resource.Resource; import io. rong. app. r; import io. rong. imkit. rongContext; import io. rong. imkit. model. providerTag; import io. rong. imkit. model. UIMessage; import io. rong. imkit. widget. asyncImageView; import io. rong. imkit. widget. provider. IContainerItemProvider; import io. rong. imlib. model. message; import io. rong. message. fileMessage;/*** Created by Bob on 15/12/24. * // @ ProviderTag (messageContent = FileMessage. class, showPortrait = true, showProgress = true, centerInHorizontal = false) public class FileMessageProvider extends IContainerItemProvider. messageProvider
  
   
{/*** Initialize View */@ 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 bind View (View v, int position, FileMessage content, UIMessage message) {final ViewHolder holder = (ViewHolder) v. getTag (); if (message. getMessageDirection () = Message. messageDirection. SEND) {v. setBackgroundResource (io. rong. imkit. r. drawable. rc_ic_bubble_no_right);} else {v. setBackgroundResource (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 (); Message. sentStatus status = message. getSentStatus (); if (status. equals (Message. sentStatus. SENDING) & progress <100) {if (progress = 0) holder. message. setText (RongContext. getInstance (). getResources (). getString (io. rong. imkit. r. string. rc_waiting); else holder. message. setText (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 ;}}
  
FileMessageProvider is responsible for controlling the class of UI display styles. A file style is used for display here. If a red packet is sent, the resource image may be changed to a red packet style image, the UI display of the upload progress is also in this class. SendFileProvider
Package io. rong. app. message. provider; import android. content. context; import android. content. intent; import android. graphics. drawable. drawable; import android.net. uri; import android. util. log; import android. view. view; import android. widget. toast; import java. io. file; import io. rong. imkit. rongContext; import io. rong. imkit. rongIM; import io. rong. imkit. widget. provider. inputProvider; import io. rong. imlib. rongIMCl Ient; import io. rong. imlib. model. conversation; import io. rong. imlib. model. message; import io. rong. message. fileMessage;/*** Created by AMing on 15/12/24. * Company RongCloud */public class SendFileProvider extends InputProvider. extendProvider {private static final String TAG = SendFileProvider. class. getSimpleName (); private Context context;/*** instantiate the adapter. ** @ Param context refers to the cloud IM context. (Through RongContext. getInstance () can be obtained) */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 "file" ;}@ Override public void onPluginClick (View View) {// Intent intent = new Intent (Intent. ACTION_GET_CONTENT); // intent. setType (ContactsContract. contacts. CONTENT_ITEM_TYPE); // startActivityForResult (intent, 1); 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, resultCo De, data); if (data! = Null) {if (data. getData (). getScheme (). equals ("file") {String s = data. getData (). getPath (); Uri uri = data. getData (); File file = new File (s); if (file. exists () {Log. e ("file", "f is a file and exists"); Conversation conversation = getCurrentConversation (); sendFile (conversation. getConversationType (), conversation. getTargetId (), file, uri);} else {Toast. makeText (context, "the file does not exist", Toast. LENGTH_SHORT) ;}}} pr Ivate void sendFile (Conversation. ConversationType conversationType, String id, File file, Uri uri) {if (RongIM. getInstance ()! = Null & RongIM. getInstance (). getRongIMClient ()! = Null) {// TODO file message Log. e ("tag", ""); Uri themUri = Uri. parse ("file: // sdcard/bob/bob.zip"); // Uri localUri = Uri. parse ("file: // sdcard/bob/bob.zip"); FileMessage fileMessage = FileMessage. obtain (uri, uri); // ImageMessage fileMessage = ImageMessage. obtain (themUri, localUri); RongIM. getInstance (). getRongIMClient (). sendImageMessage (Conversation. conversationType. PRIVATE, id, fileMessage, null, null, new RongIMClient. sendImageMessageCallback () {@ Override public void onAttached (Message message) {Log. e (TAG, "------------- onAttached --------") ;}@ Override public void onError (Message message, RongIMClient. errorCode code) {Log. e (TAG, "---------------- onError -----" + code) ;}@ Override public void onSuccess (Message message) {Log. e (TAG, "------------------ onSuccess ---") ;}@ Override public void onProgress (Message message, int progress) {Log. e (TAG, "----------------- onProgress ----" + progress );}});}}}
This class is the entry class for sending files. Please note that. in this Code, the File Manager of the Android system is directly enabled. In some Android-based custom models, it is recommended that Samsung Xiaomi, the Android native model, be enabled without any files. here, you can customize scan filters to write custom file managers. Ohter Code: After sharing the three core classes, let's talk about registering message types and registering message templates in other related Code application classes. This step is simple but easy to forget.
RongIM.registerMessageType(FileMessage.class);RongIM.registerMessageTemplate(newFileMessageProvider());
Click the listener to determine the file message.
if(message.getContent() instanceof FileMessage) {            FileMessage fileMessage = (FileMessage) message.getContent();            if (message.getMessageDirection().equals(io.rong.imlib.model.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);            }        }
The file message is determined here and then jumps to the download page for download. Summary:

The implementation effects and implementation principles and general code have been shared above, but it is recommended that you do not copy all of the code. You still need to understand it and implement it yourself. for example, the upload and download method implements the logic of interacting with your server or cloud storage. Finally, I hope this article will help you! End ~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.