Message API

Pre-built customizable chat UI - Message API

This section will guide you in using our ready-made UI. If you are looking to build your own UI using our features, you can refer to Build your UI from scratch - Message API.

Open your Activity on tap of toolbar in Chat Screen

To open a certain activity on tap of the toolbar in chat screen add the following in you AndroidManifest.xml file:

<meta-data
    android:name="com.applozic.mobicomkit.uiwidgets.toolbar.tap.activity"
    android:value="PUT_ACTIVITY_CLASS_HERE" />

This activity will receive the userId of the selected chat in intent.

Send Message

You can send a message to a userId as below:
Make the following import:

import com.applozic.mobicomkit.api.conversation.MobiComConversationService;

Send a message:

new MobiComConversationService(activity).sendMessage(new Message("[email protected]", "hello test"));
MobiComConversationService(context).sendMessage(Message("testReceiverUserId", "hello test"))

Send message with metadata

You can send extra information along with message text as meta-data. These key-value pairs can be used to do some extra processing or keep information about messages.

MobiComUserPreference userPreferences = MobiComUserPreference.getInstance(context);
        Message message = new Message();
        //Note:This is only for sending a message to Group then pass the channelKey
        message.setGroupId(channelKey);  

        //Note:This is only for sending a message to User then pass the receiver UserId 
        message.setTo(receiverUserId); 
        message.setContactIds(receiverUserId); 

        message.setRead(Boolean.TRUE);
        message.setStoreOnDevice(Boolean.TRUE);
        message.setCreatedAtTime(System.currentTimeMillis() + userPreferences.getDeviceTimeOffset());
        message.setSendToDevice(Boolean.FALSE);
        message.setType(Message.MessageType.MT_OUTBOX.getValue());
        message.setMessage(messageToSend); //Message to send
        message.setDeviceKeyString(userPreferences.getDeviceKeyString());
        message.setSource(Message.Source.MT_MOBILE_APP.getValue());

       //Messsage metadata map 
        Map<String,String> messageMetaDataMap = new HashMap<>();
        messageMetaDataMap.put("key1","value1");
        messageMetaDataMap.put("key2","value2");
        message.setMetadata(messageMetaDataMap);

        //Method for sending a message 
        new MobiComConversationService(context).sendMessage(message);
val userPreferences = MobiComUserPreference.getInstance(context)
val message = Message()
//Note:This is only for sending a message to Group then pass the channelKey
//Note:This is only for sending a message to Group then pass the channelKey
message.groupId = channelKey

//Note:This is only for sending a message to User then pass the receiver UserId

//Note:This is only for sending a message to User then pass the receiver UserId
message.to = "receiverUserId"
message.contactIds = "receiverUserId"

message.isRead = Boolean.TRUE
message.isStoreOnDevice = Boolean.TRUE
message.createdAtTime = System.currentTimeMillis() + userPreferences.deviceTimeOffset
message.isSendToDevice = Boolean.FALSE
message.type = Message.MessageType.MT_OUTBOX.value
message.message = "Message to send" //Message to send

message.deviceKeyString = userPreferences.deviceKeyString
message.source = Message.Source.MT_MOBILE_APP.value

//Message metadata map
val messageMetaDataMap: MutableMap<String, String> = HashMap()
messageMetaDataMap["key1"] = "value1"
messageMetaDataMap["key2"] = "value2"
message.metadata = messageMetaDataMap

        //Method for sending a message
MobiComConversationService(context).sendMessage(message)

Send a message with an attachment

You can send an attachment with a message as below:

Message message = new Message();
List<String> filePaths = new ArrayList<>();
filePaths.add(filePath1); // You can add any number of filePaths to this
            message.setTo(userID); //use this for individual
            message.setContactIds(userID); //use this for individual
            message.setGroupId(groupId); //use this for group
            message.setContentType(Message.ContentType.ATTACHMENT.getValue());
            message.setFilePaths(filePaths);

            if (textMessage != null && !TextUtils.isEmpty(textMessage)) {
                message.setMessage(textMessage);
            }// you can also add text message with the attachment
new MobiComConversationService(context).sendMessage(message);
val userPreferences = MobiComUserPreference.getInstance(context)
val message = Message()
val filePaths: MutableList<String> = ArrayList()
filePaths.add(filePath) // You can add the file path to this

// Sending a message in one to one  set the receiver UserId and comment the message.groupId
message.to = "receiverUserId" //use this for individual
message.contactIds = "receiverUserId" //use this for individual

message.deviceKeyString = userPreferences.deviceKeyString

// Sending a message in group chat comment the  message.to  and  message.contactIds
 message.groupId = groupId //use this for group

message.contentType = Message.ContentType.ATTACHMENT.getValue()
message.filePaths = filePaths

// message.message = textMessage  // you can also add text message with the attachment
MobiComConversationService(context).sendMessage(message)

Following attachment types are supported in our pre-built UI ::

  • Audio
  • Video
  • PDF
  • Image
  • GIF
  • DOC
  • Location
  • Contact

You will have to do minor changes in above code for sending different types of attachment.

/// For sending Audio use contentType :: 
message.setContentType(Message.ContentType.AUDIO_MSG.getValue());

/// For sending Video use contentType :: 
message.setContentType(Message.ContentType.VIDEO_MSG.getValue());

/// For sending Contact use contentType ::
message.setContentType(Message.ContentType.CONTACT_MSG.getValue());

/// For sending Image/GIF/PDF/DOC use contentType ::
message.setContentType(Message.ContentType.ATTACHMENT.getValue());

/// For sending location, use below message object ::
Message message = new Message();
message.setTo(userID); //use this for individual
message.setContactIds(userID); //use this for individual
message.setGroupId(groupId); //use this for group
message.setContentType(Message.ContentType.LOCATION.getValue());
message.setMessage("{\"lat\":12.9403722,\"lon\":77.6253097}")
new MobiComConversationService(context).sendMessage(message);
val message = Message()
/// For sending Audio use contentType ::
 message.contentType = Message.ContentType.AUDIO_MSG.value;

/// For sending Video use contentType ::
message.contentType = Message.ContentType.VIDEO_MSG.value;

/// For sending Contact use contentType ::
message.contentType = Message.ContentType.CONTACT_MSG.value;

/// For sending Image/GIF/PDF/DOC use contentType ::
 message.contentType = Message.ContentType.ATTACHMENT.value;

/// For sending location, use below message object ::
message.to = userID; //use this for individual
message.contactIds = userID; //use this for individual
message.groupId = groupId; //use this for group
message.contentType = Message.ContentType.LOCATION.value;
message.message = "{\"lat\":12.9403722,\"lon\":77.6253097}"
MobiComConversationService(context).sendMessage(message);

📘

Use either contactId or groupId to create a message object.

📘

Note: If you upload a file on our servers then there is a size limit of 100 MB. This limit can be increased on request.

Messages list

You can access the message list as below:
Make the following import:

import com.applozic.mobicomkit.api.conversation.MobiComConversationService;
  • To get single latest message from each conversation:
public synchronized List<Message> getLatestMessagesGroupByPeople() {            
  ...         
 }
val messageList = MobiComConversationService(context).latestMessagesGroupByPeople
  • To get messages of logged in user with another user by passing userId, startTime and endTime. startTime and endTime are considered as time in milliseconds from 1970:
public List<Message> getMessages(String userId, Long startTime, Long endTime) {            
  ...           
 }
// One to one chat thread conversations 
val contactService = AppContactService(this)
val contact = contactService.getContactById(userId)

// To get the message of the user pass the start time of first message
val messageList =  MobiComConversationService(context).getMessages(startTime, null, contact, null, null)

// Pass the endTime last message createAtTime
val oldChatMessages =  MobiComConversationService(context).getMessages(null, endTime, contact, null, null)
        

//  Group chat thread messages
 val channelService = ChannelService.getInstance(context)
 val channel = channelService.getChannelByChannelKey(channelKey)

// To messages of the group pass the start time of first message
 val messageList =  MobiComConversationService(context).getMessages(startTime, null, null, channel, null)


// Pass the endTime last message createAtTime
 val oldChatMessages =  MobiComConversationService(context).getMessages(null, endTime, null, channel, null)

Note: Make sure to call the above methods in a background task as they are server calls won't run on the main thread.

Build your UI from scratch - Message API

Sending a message

You can send a message to a user or a group using MessageBuilder. Use the below code to send a simple text message to a user.

new MessageBuilder(context).setMessage("Hello there").setTo(userId).send();
MessageBuilder(context).setMessage("Hello there").setTo(userId).send();

To send a message with metadata to the user.

Map<String,String> metadata = new HashMap<>();
metadata.put("key1","value1");
metadata.put("key2","value2");

new MessageBuilder(context)
  .setMessage("Hello there")
  .setTo(userId)
  .setMetadata(metadata)
  .send();
val metadata: MutableMap<String, String> = HashMap()
     metadata["key1"] = "value1"
     metadata["key2"] = "value2"
MessageBuilder(context)
        .setMessage("Hello there")
        .setTo(userId)
        .setMetadata(metadata)
        .send()

To send a simple text message to a group, use the below code:

new MessageBuilder(context).setMessage("Hello there").setGroupId(123456).send();
MessageBuilder(context)
               .setMessage("Hello there")
               .setGroupId(123456)
               .send();

To send a message with Attachment use the below code:

new MessageBuilder(context)
                .setContentType(Message.ContentType.ATTACHMENT.getValue())
                .setGroupId(12345)
                .setFilePath("the file's absolute path in string")
                .send();
MessageBuilder(context)
               .setContentType(Message.ContentType.ATTACHMENT.value)
               .setGroupId(12345)
               .setFilePath("the file's absolute path in string")
               .send();

To send a message with metadata to the group.

Map<String,String> metadata = new HashMap<>();
metadata.put("key1","value1");
metadata.put("key2","value2");

new MessageBuilder(context)
  .setMessage("Hello there")
  .setGroupId(12345)
  .setMetadata(metadata)
  .send();
val metadata: MutableMap<String, String> = HashMap()
    metadata["key1"] = "value1"
    metadata["key2"] = "value2"

MessageBuilder(context)
              .setMessage("Hello there")
              .setGroupId(12345)
              .setMetadata(metadata)
              .send()

Following attachment types are supported:

  • Audio
  • Video
  • PDF
  • Image
  • GIF
  • DOC
  • Location
  • Contact

This how you can set the type based on the attachment which your sending in a message

You need to set the content type in MessageBuilder object creation

/// For sending Audio use contentType :
new MessageBuilder(context).setContentType(Message.ContentType.AUDIO_MSG.getValue())

/// For sending Video use contentType :
new MessageBuilder(context).setContentType(Message.ContentType.VIDEO_MSG.getValue())

/// For sending Contact use contentType :
new MessageBuilder(context).setContentType(Message.ContentType.CONTACT_MSG.getValue())

/// For sending Image/GIF/PDF/DOC use contentType :
new MessageBuilder(context).setContentType(Message.ContentType.ATTACHMENT.getValue())
/// For sending Audio use contentType :
MessageBuilder(context).setContentType(Message.ContentType.AUDIO_MSG.value)

/// For sending Video use contentType :    MessageBuilder(context).setContentType(Message.ContentType.VIDEO_MSG.value)

/// For sending Contact use contentType :
MessageBuilder(context).setContentType(Message.ContentType.CONTACT_MSG.value)

/// For sending Image/GIF/PDF/DOC use contentType :
MessageBuilder(context).setContentType(Message.ContentType.ATTACHMENT.value)

📘

Note: If you upload a file on our servers then there is a size limit of 100 MB. This limit can be increased on request.

To send a message with Contact use the below code:

new MessageBuilder(context)
                .setContentType(Message.ContentType.CONTACT_MSG.getValue())
                .setGroupId(12345)
                .setFilePath("the contact vcf file's absolute path in string")
                .send();
MessageBuilder(context)
               .setContentType(Message.ContentType.CONTACT_MSG.value)
               .setGroupId(12345)
               .setFilePath("the contact vcf file's absolute path in string")
               .send();

To send a location message, use the below code:

new MessageBuilder(context)
                .setContentType(Message.ContentType.LOCATION.getValue())
                .setGroupId(12345)
                .setMessage("{\"lat\":12.9403722,\"lon\":77.6253097}")
                .send();
MessageBuilder(context)
                .setContentType(Message.ContentType.LOCATION.value)
                .setGroupId(12345)
                .setMessage("{\"lat\":12.9403722,\"lon\":77.6253097}")
                .send();

You can also send a message with both text and attachment:

new MessageBuilder(context)
                .setMessage("Look at this")
                .setContentType(Message.ContentType.ATTACHMENT.getValue())
                .setGroupId(12345)
                .setFilePath("the file's absolute path in string")
                .send();
MessageBuilder(context)
                .setMessage("Look at this")
                .setContentType(Message.ContentType.ATTACHMENT.value)
                .setGroupId(12345)
                .setFilePath("the file's absolute path in string")
                .send()

Handling the Attachment Upload progress

You can send a message using the MessageBuilder and get the upload progress in percentage for the attachment attached to the message. The MediaUploadProgressHandler will give you the upload progress update for the same. Use the below code:

new MessageBuilder(context)
                .setContentType(Message.ContentType.ATTACHMENT.getValue())
                .setGroupId(12345)
                .setFilePath("the files absolute path in string")
                .send(new MediaUploadProgressHandler() {
                    @Override
                    public void onUploadStarted(ApplozicException e, String oldMessageKey) {
                        if(e == null){
                          //the upload has started
                        }
                    }

                    @Override
                    public void onProgressUpdate(int percentage, ApplozicException e, String oldMessageKey) {
                       if(e == null){
                         //display this upload percentage on the UI
                       }
                    }

                    @Override
                    public void onCancelled(ApplozicException e, String oldMessageKey) {
                        //the upload was interrupted, most of the times by the user
                    }

                    @Override
                    public void onCompleted(ApplozicException e, String oldMessageKey) {
                       if(e == null){
                         //The upload has finished
                       }else{
                        //The upload has failed, due to network error or server error
                       }
                    }

                    @Override
                    public void onSent(Message message, String oldMessageKey) {
                      //The message containing the attachment has been sent to the server.
                    }
                });
MessageBuilder(context)
                .setContentType(Message.ContentType.ATTACHMENT.value)
                .setGroupId(12345)
                .setFilePath("the files absolute path in string")
                .send(object : MediaUploadProgressHandler {
                    override fun onUploadStarted(e: ApplozicException?, oldMessageKey: String?) {
                        if (e == null) {
                            //the upload has started
                        }
                    }

                    override fun onProgressUpdate(percentage: Int, e: ApplozicException?, oldMessageKey: String?) {
                        if (e == null) {
                            //display this upload percentage on the UI
                        }
                    }

                    override fun onCancelled(e: ApplozicException?, oldMessageKey: String?) {
                        //the upload was interrupted, most of the times by the user
                    }

                    override fun onCompleted(e: ApplozicException?, oldMessageKey: String?) {
                        if (e == null) {
                            //The upload has finished
                        } else {
                            //The upload has failed, due to network error or server error
                        }
                    }

                    override fun onSent(message: Message, oldMessageKey: String?) {
                        //The message containing the attachment has been sent to the server.
                    }
                })

Here the oldMessageKey is the parameter which you will require to search the message in the current adapter and then update the same from the callbacks.
You can use an interface to update the progress on the adapter from the callbacks.

Callback for sent message

The callback will be received in onMessageSent(Message message) callback method of ApplozicUIListener. Please go through this section of the doc to implement the listener. The method will automatically update the message in local database, you just need to worry about updating it on UI.

You can either reload the message list or add the message to existing list and notify the adapter.

@Override
    public void onMessageSent(Message message){
      //use this method to add the latest message to your chat list adapter
        ApplozicConversation.addLatestMessage(message, messageList);
        yourAdapter.notifyDatasetChanged();
      
      //here you can check what the callback was for
      if(message.isSentToServer()){
        //show sent icon
      }else{
        //show pending icon
      }
      
    }
override fun onMessageSent(message: Message?) {
        if (message != null) {
            ApplozicConversation.addLatestMessage(message, messageList)
            yourAdapter.notifyDatasetChanged()

            //here you can check what the callback was for
            if (message.isSentToServer) {
                //show sent icon
            } else {
                //show pending icon
            }
        }
}

Receiving a message

You can receive a message in real time using ApplozicUIListener. Please go through this section of the doc to implement the listener. There are some methods you need to override from the listener. The onMessageReceived(Message message) method will provide the message received. The message will be automatically updated in local database.

You can either reload the message list or add the message to existing list and notify the adapter.

@Override
    public void onMessageReceived(Message message) {
        //when a new message is received. You could reload the latest message list or add this message to the existing message list to update this message on UI.
    }
override fun onMessageReceived(message: Message?) {
        //when a new message is received. You could reload the latest message list or add this message to the existing message list to update this message on UI.
    }

Adding a message in the existing latest message list

If you want to add a new message to the existing list that is currently displayed by your adapter, then Applozic provides a simple method to do that. You can add a new Message to the list by calling the below method:

ApplozicConversation.addLatestMessage(message, messageList);
yourAdapter.notifyDatasetChanged();
ApplozicConversation.addLatestMessage(message, messageList)
 yourAdapter.notifyDatasetChanged()

Where message is the latest message you want to add in the list
messageList is the existing list attached to your list adapter.

📘

Note

addLatestMessage should only be called to add message in the latest message list and not in the individual message thread list. Since the latest message list needs some manipulation after a message is sent or received. On the other hand the individual message thread list just stacks up the messages from bottom of the list for the same contact/group, hence the use of this method will empty up the list and just show the latest message.

Handling the attachment download progress

You can download the attachment for a message using the below code. The MediaDownloadProgressHandler gives the callback with the download progress.

ApplozicConversation.downloadMessage(context, message, new MediaDownloadProgressHandler() {
           @Override
           public void onDownloadStarted() {
              //The download has started
           }

           @Override
           public void onProgressUpdate(int percentage, ApplozicException e) {
             if(e == null){
               //update the percentage on the UI for the message
             }
           }

           @Override
           public void onCompleted(Message message, ApplozicException e) {
              if(e == null && message != null){
                //the download has completed successfully, you can access the attachment using the filePath from the message
                String filePath = message.getFilePaths().get(0);
              }
           }
       });
ApplozicConversation.downloadMessage(context, message, object : MediaDownloadProgressHandler {
            override fun onDownloadStarted() {
                //The download has started
            }

            override fun onProgressUpdate(percentage: Int, e: ApplozicException?) {
                if (e == null) {
                    //update the percentage on the UI for the message
                }
            }

            override fun onCompleted(message: Message?, e: ApplozicException?) {
                if (e == null && message != null) {
                    //the download has completed successfully, you can access the attachment using the filePath from the message
                    val filePath = message.filePaths[0]
                }
            }
})

Message read and delivered for a group

Use the below method in Async task or thread to get a delivered and read userId list need to pass the key message in place of MESSAGE_KEY from the message object you can get the key message.getKeyString().

🚧

Call the below method in Async task or any thread

As the below method won't get the result on the main thread you need to call it in an async task or any other background thread to get the response

MessageInfoResponse messageInfoResponse = new MobiComMessageService(this, MessageIntentService.class).getMessageInfoResponse(MESSAGE_KEY);

        List<MessageInfo> deliveredUserList = messageInfoResponse.getDeliverdToUserList();

        if (deliveredUserList != null) {
            // example you can get the userId like below
            for (MessageInfo info : deliveredUserList) {
                Log.i("Delivered", "Message info userId for Delivered:" + info.getUserId());
            }
        }

        List<MessageInfo> readUserList = messageInfoResponse.getReadByUserList();

        if (readUserList != null) {
            // example you can get the userId like below

            for (MessageInfo info : readUserList) {
                Log.i("Read", "Message info userId for read:" + info.getUserId());
            }
        }
val messageInfoResponse = MobiComMessageService(context, MessageIntentService::class.java).getMessageInfoResponse(MESSAGE_KEY)
  
if (messageInfoResponse != null) {
    val deliveredUserList: List<MessageInfo>? = messageInfoResponse.deliverdToUserList

    if (deliveredUserList != null) {
        // example you can get the userId like below
        for (info in deliveredUserList) {
          Log.i("Delivered", "Message info userId for Delivered:" + info.userId)
        }
    }

val readUserList: List<MessageInfo>? = messageInfoResponse.readByUserList

    if (readUserList != null) {
       // example you can get the userId like below
       for (info in readUserList) {
            Log.i("Read", "Message info userId for read:" + info.userId)
       }
    }
}

Did this page help you?