How to mark the message being received by using Smack in Android

Smack is one of the most powerful and most used libs to handling instant messages in the app development. In this article, I will be showing you how to mark the message is “received” by using Smack.

But before we go through the code, let’s try to answer a question: If you were the guy who maintaining or creating this lib, and were trying to make a feature to mark the received message, what would you do?

At least if I were the maintainer, I would create a Listener to receive the message containing the info that “the contact has received your message” (let’s call it Receipt). And also I would like to add an ID field to tell the app which message has been received, as there might be about hundreds of messages in the chat page, but the order of the Receipts is probably not the same as the order of the messages being sent to the contact (which is very important!).

If you have understood the concept above, I think it is enough for you to build a simple chat page with the least functions. Let’s go through the code.

Let’s say you have a Fragment, let’s call it ChatFragment, and now you need a Listener to receive the receipts. Fortunately Smack provides an interface called ReceiptReceivedListener. By clicking the hyper-link you can find there is only one method in this listener and it gently contains the receiptId which can be used to match the messages.

So, the code would be something like:

public class ChatFragment extends Fragment implements
ReceiptReceivedListener {
    private DeliveryReceiptManager mDeliveryReceiptManager;
public void onReceiptReceived(String fromJid, String toJid,
String receiptId, Stanza receipt) {
        if (isAdded()) {
// do something you like
public void onCreate(Bundle savedInstanceState) {
        mDeliveryReceiptManager = DeliveryReceiptManager.getInstanceFor(
public void onDestroyView() {
        if(mDeliveryReceiptManager != null)

But wait, what is the receiptId and how can you know the receiptId before the message being sent? Actually if you are trying to implement the function of “marking the received messages”, you must have done the function of “sending messages”. And when you send the Message object by using XMPPConnection, you can find there is a messageId being generated itself, which actually is the receiptId!

So easy, huh?

(I wrote it is because there is a question to answer on stackoverflow:

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.