Write your First mesibo Enabled Application - Android

Estimated reading time: 23 minutes

In this part, we will create a simple real-time app in Android. In this process, we will also learn about using different types of mesibo APIs. Here is a brief overview of what we will learn in this part.

Please go through the following prerequisites before you read further.

Prerequisites

  • Read the section Create Users to learn about creating an app in mesibo console and creating users & access tokens for your app.
  • Knowledge of using Android Studio and making basic Android Apps
  • Download the source code for the First mesibo Android App from GitHub.

First Android App

Now let’s quickly start coding:

  1. Start Android Studio.
  2. Create a new project with a minimum SDK version 16 or higher.
  3. Android Studio starts Gradle and builds your project. This may take a few seconds. For more information about creating a project in Android Studio, see the Android Studio documentation. https://developer.android.com/training/basics/firstapp/creating-project.html
  4. Add mesibo SDK to your project by adding gradle dependency and performing gradle sync as explained in installation instructions. Import mesibo API.
  5. Create two users, each with the User Address 123 and 456 and App ID com.mesibo.firstapp. You can refer to the section Create Users to learn how to create users.
  6. Modify the token values in the source code to the ones you have generated for each of your demo users. For example, in Java
    DemoUser mUser1 = new DemoUser("xyz", "User-1", "123");
    DemoUser mUser2 = new DemoUser("pqr", "User-2", "456");
    

    Example, in Kotlin

    internal var mUser1 = DemoUser("xyz", "User-1", "123")
    internal var mUser2 = DemoUser("pqr", "User-2", "456")
    
  7. Initialize mesibo for each user, when they log in.

Initialize mesibo

Before you send and receive real-time messages and calls, you need to initialize mesibo. The initialization involves the following steps:

  1. Use setAccessToken to set the user’s access token that you obtained while creating the user
  2. Set up mesibo to invoke your listener class using addListener
  3. Set up database to store sent and received messages using setDatabase (Optional)
  4. Start mesibo

Sample mesibo initialization code, using Java in MainActivity.java

Mesibo api = Mesibo.getInstance();
api.init(getApplicationContext());

Mesibo.addListener(this);
Mesibo.setSecureConnection(true);
Mesibo.setAccessToken(user.token);
Mesibo.setDatabase("mydb", 0);

Mesibo.start();

//... Refer to the Sample Code on GitHub ...//

Sample mesibo initialization code, in MainActivity.kt

val api: Mesibo = Mesibo.getInstance()
api.init(applicationContext)

Mesibo.addListener(this)
Mesibo.setSecureConnection(true)
Mesibo.setAccessToken(user.token)
Mesibo.setDatabase("mydb", 0)

Mesibo.start()

//... Refer to the Sample Code on GitHub...//

Extend your activity to Implement mesibo.MessageListener and mesibo.ConnectionListner class and implement listeners. The easiest way is to click on the Code menu and click on Implement Methods and it will automatically generate the code for all the methods.

Sample mesibo Listeners in Java,

public class MainActivity extends AppCompatActivity implements mesibo.MessageListener, 
       Mesibo.ConnectionListener  {
    
    @Override
    public void Mesibo_onConnectionStatus(int status) {
        // You will receive the connection status here
        Log.d(TAG, "on Mesibo Connection: " + status);
    }

    @Override
    public boolean Mesibo_onMessage(Mesibo.MessageParams params, byte[] data) {  
        // You will receive messages here
       return true;
    }

    @Override
    public void Mesibo_onMessageStatus(Mesibo.MessageParams params) {
        // You will receive status of sent messages here

    }
}

Sample mesibo Listeners in Kotlin,

 override fun Mesibo_onConnectionStatus(status: Int) {
     // You will receive the connection status here
 }

 override fun Mesibo_onMessage(messageParams: Mesibo.MessageParams?, data: ByteArray?): Boolean {
     // You will receive the connection status here
 }
 
 override fun Mesibo_onMessageStatus(messageParams: Mesibo.MessageParams) {
     // You will receive the status of sent messages here
 } 

That’s it - you are now ready to send and receive your first real-time message.

Testing your first application

  1. Build and Install the Application.
  2. On the demo app, click on the Login as User1 button.
  3. Mesibo_OnConnectionStatus should cycle through various status information. Finally, you should receive status=1 which indicates that your app is successfully connected to the mesibo real-time server and ready to send and receive real-time messages. If you are not getting connection status 1, and getting 4 or 5, you are not passing the correct appid while creating a token. The appid passed to create a token must match the Android package name declared in the AndroidManifest.xml (for example, com.mesibo.xxx). Also, if you are using google-services.json in your project, ensure that the package name matches.

  4. We will use mesibo console to send a test message. In a later section, we will learn how to send messages from the app itself.
    • Go to Console ->Application->Users. You should see the user you have created.
    • Go to user details by clicking the Edit button. Scroll down, you will see a section to Message User
    • Enter 1000 (or anything) in the From field, check Create This User checkbox, type the message and click on Send.
  5. You will instantly receive this message in your mobile app and the message will be displayed in a toast. If you check the logs, you can see that you got the message in Mesibo_OnMessage listener.

Sending and Receiving Messages

In the previous section, we have used mesibo console to send a message. Now we will quickly learn how to send messages from the app itself.

To send messages, we will use sendMessage real-time API for which we will need destination user, message-id, and the message itself. Invoke the following function anywhere from your code to send a text message. In a later section, we will learn how to send rich messages.

In Java,

public void onSendMessage(View view) {
    Mesibo.MessageParams p = new Mesibo.MessageParams();
    p.peer = mRemoteUser.address;
    p.flag = Mesibo.FLAG_READRECEIPT | Mesibo.FLAG_DELIVERYRECEIPT;

    Mesibo.sendMessage(p, Mesibo.random(), mMessage.getText().toString().trim());
}

In Kotlin,

fun onSendMessage(view: View?) {
    val p: Mesibo.MessageParams = Mesibo.MessageParams()
    p.peer = mRemoteUser!!.address
    p.flag = Mesibo.FLAG_READRECEIPT or Mesibo.FLAG_DELIVERYRECEIPT
    Mesibo.sendMessage(p, Mesibo.random(), mMessage!!.text.toString().trim { it <= ' ' })
}

Once you send a message, the recipient will receive the message through Mesibo_OnMessage. mesibo will inform the sender of the message about the status of the message - sent, delivered, or read through the listener Mesibo_onMessageStatus.

Voice and Video Calls

mesibo allows you to enable peer-to-peer HD video and voice calls between your users in just a few lines of code. As with messaging, mesibo video and voice calls are encrypted and hence secure. mesibo does not bill any additional amount for the voice or video call API.

Making and receiving voice & video calls with mesibo is simple. You only need to initialize MesiboCall once using just two lines of code! Then, mesibo will automatically handle incoming calls. For outgoing calls, you can invoke call API as required.

You can use mesibo voice and video calls as it is. But, if you wish, you can customize it to your needs. For example, you can customize the call screen UI, filter incoming calls, etc. Refer to Call API Reference to learn more.

To initialize in Java

MesiboCall.init(context);
MesiboCall.getInstance().setDefaultUiTitle('your app name');

To make a call in Java

MesiboCall.getInstance().callUi(this, address, true);

Initialization In Kotlin

MesiboCall.getInstance().init(applicationContext)
MesiboCall.getInstance().setDefaultUiTitle('mesibo first app')

To make a call in Kotlin

MesiboCall.getInstance().callUi(this, address, true)

In the first app tutorial we have now learned about two of the most fundamental mesibo APIs - the messaging API and call API. In the upcoming sections, we will learn more about various mesibo APIs and features that you can use. Such as group messaging, group calls, reading stored messages, UI Modules, etc.

Group Messaging and Group Calls

In this section, we will learn about group messaging and group calls(conferencing). The group messaging API is similar to the one-to-one messaging API and the group call API is similar to the one-to-one voice and video call API.

Group Messaging

You can invoke one of the messaging APIs to send a group message, just like the way you used the one-to-one messaging API. Here, instead of the user’s address you need to specify the groupid. To send messages to a group, you need it’s groupid.

To create a group and add members, you need to use the Group Management APIs. This is the recommended approach. However, you can also create a group and members in the mesibo console

Group Management APIs

Creating a Group

To create a group, use the groupadd REST API, which is a part of Group Management APIs.

For example,

https://api.mesibo.com/api.php?op=groupadd&token=123434343xxxxxxxxx&name=testGroup&flag=0

If group creation is successful, you should receive a response that looks like below

{..<truncated>.. ,"group":{"gid":102529},"op":"groupadd","result":true}

To learn more about groupadd parameters and creating different types of groups by setting different group permissions, see Group Management APIs - groupadd

groupadd REST API

If you would like to create a group using the console, Go to your App Settings and click on Groups. Then, click on the + NEW GROUP button. Give a group name - example Mesibo Group and click on Create. Your group with the name Mesibo Group should now be created and be displayed in the table. Click on the edit icon, under actions. This will open the Group Settings page. Replicate settings shown below.

Group Permissions

Adding members to a Group

To add members to a group, use the groupeditmembers REST API, which is a part of Group Management APIs.

For example,

https://api.mesibo.com/api.php?op=groupeditmembers&token=123434343xxxxxxxxx&gid=102529&m=member1,member2,member3&delete=0

To learn more about groupeditmembers parameters, deleting group members, and setting member level permissions, see Group Management APIs - groupeditmembers

groupeditmembers REST API

The users you add should be existing mesibo users. Otherwise, create those users before you try to add them.

If you would like to add members to a group using the console, Go to your App Settings and then click on Groups. Open the group you want to edit, and then Click on the + NEW MEMBER button. Enter the address of the user whom you wish to add. Click on Add. The Members table will now display the member you just added. Similarly, add more users.

Group Members

If you successfully create a group, you will get a groupid. Once you get a groupid, you can use it to send a group message to the group and all members of the group will receive the group message.

For example, here is an example of how you can send a message to a group. Let’s say you have a group with the group-id 96568. Now, you use the same function that you use for sending a one-to-one message, where instead of setting the peer to the user address, now you set it to the group-id.

Using Java,

Mesibo.MessageParams p = new Mesibo.MessageParams();
p.groupid = 96568;
p.flag = Mesibo.FLAG_READRECEIPT | Mesibo.FLAG_DELIVERYRECEIPT;
String message = "This is a group message";     
Mesibo.sendMessage(p, Mesibo.random(), message);

Using Kotlin,

p.peer = mRemoteUser!!.address
p.flag = Mesibo.FLAG_READRECEIPT or Mesibo.FLAG_DELIVERYRECEIPT
private val message = "This is a group message"
Mesibo.sendMessage(p, Mesibo.random(), message)

A message sent will be delivered to all members of the group and you will get the message delivery and read status for each user.

Group Calls (Conferencing)

mesibo group calling simply extends the existing features of group messaging with additional permissions and control, for example, room resolution, talk detection, who can publish and who can video, voice+video or voice only, etc. Your existing groups will now have additional conferencing settings.

To add mesibo Group Calling to your app, here is an overview of steps to follow:

  1. Have a group of members with required permissions
  2. Create a group call object with groupCall()
  3. To publish your stream to the group, get a Participant object using createPublisher and make a call()
  4. To subscribe to other users’ streams, get their call object in MesiboGroupCall_OnPublisher and make a call()
  5. Display the stream using setVideoView

For detailed documentation and examples for conferencing refer to Mesibo Conferencing Docs and download the example source code for conferencing from Github

You can also try a live demo of a Zoom-like conferencing app, Mesibo Live built using mesibo conferencing and streaming API. The source code of the app is available on Github. You can download it, modify or rebrand it, and integrate it into your app or website.

Reading Messages

mesibo provides a set of APIs deal with stored messages in the database and sending read receipts. A read receipt is an acknowledgment that the user has read the message.

To read stored messages from the database, you need to create a read session and set the criteria to read messages; for example,

  • read all messages
  • read messages from a sender
  • read messages for a particular group
  • read messages matching a search query etc.

The read session you create filters the messages in the database based on the criteria provided and gives the resulting list of messages to you.

Reading Modes

There are two modes of operation:

  • Read Messages and call logs. This mode is enabled by default
  • Read Summary (active conversations), read the latest message from each user and group. This allows you to get a snapshot of all the communicating users and groups. You can then create another read session to read messages for any of those users or groups.

Reading Order

Once you set a read session, you can start reading messages by calling read API. You can read messages in the first-in-first-out (FIFO) mode or the last-in-first-out (LIFO) mode. In the first-in-first-out model, the oldest messages are read first. By default, the first-in-first-out mode is disabled.

Read Receipts

You can enable the automatic sending of read-receipts every time you read a message. This can be achieved by enabling a read-receipt for the read session. On reading or receiving a message, read receipts will be automatically sent if

  • The app is set to be in the foreground
  • Sending Read Receipt is enabled for the reading session, AND
  • Read receipt requested by the sender, AND
  • A new real-time or database message matches the read session.

A call to read will return the number of messages read. You can call read on demand. For example, in the case of a messaging app, you only need to show the latest messages on the screen initially. So, first, you can call read(10) to load the last 10 messages. As the user scrolls up the chat history, you can call read again. All subsequent calls to read will read older messages.

To read messages for a user, in Java

// Read receipts are enabled only when App is set to be in foreground
Mesibo.setAppInForeground(this, 0, true);
Mesibo.ReadDbSession mReadSession = new Mesibo.ReadDbSession(mUser.address, 0, null, this);
mReadSession.enableReadReceipt(true);
mReadSession.read(100);

To read messages for a group, in Java

// Read receipts are enabled only when App is set to be in foreground
Mesibo.setAppInForeground(this, 0, true);
Mesibo.ReadDbSession mReadSession = new Mesibo.ReadDbSession(null, mGroupid, null, this);
mReadSession.enableReadReceipt(true);
mReadSession.read(100);

To read the last message from each user (summary), in Java

Mesibo.ReadDbSession mReadSession = new Mesibo.ReadDbSession(null, 0, null, this);
mDbSession.enableSummary(true);
mReadSession.enableReadReceipt(false);
mReadSession.enableMissedCalls(mShowMissedCalls);
mReadSession.read(100);

To read messages for a user, in Kotlin

// Read receipts are enabled only when App is set to be in foreground
Mesibo.setAppInForeground(this, 0, true)
mReadSession = Mesibo.ReadDbSession(mRemoteUser!!.address, this)
mReadSession?.enableReadReceipt(true)
mReadSession?.read(100)

To read last message from each user (summary), in Kotlin

mReadSession = Mesibo.ReadDbSession(null, this)
mReadSession?.enableReadReceipt(true)
mReadSession?.enableMissedCalls(true)
mReadSession?.read(100)

Ready to use UI Modules

mesibo provides a variety of pre-built UI components that allow you to quickly add messaging, voice & video call graphical user interface in your app. mesibo UI modules are completely customizable. You can not only customize colors, icons, etc but also customize how each message is rendered. This enables you to create powerful chatbots in no-time.

mesibo UI modules are available as:

  • Fragment (Android)
  • ViewController (iOS)
  • Individual Views (android and ios)

One of the key advantages of mesibo UI modules is that they are well tested and you only need to write minimal code to create fully-functional UIs. Any future enhancements are also automatically available to you.

messaging group chat mesibo voice and video calls

To use mesibo UI modules, you need to perform the following steps:

  1. Add UI modules to your project
  2. Initialize mesibo API with access token as described in the Android, or iOS section
  3. Launch mesibo UI modules, for example,
MesiboUI.launch(context, 0, false, true);

That’s it.

The best way to learn how to use mesibo UI modules is to refer to the open-source messenger app for Android, iOS, and Javascript source code which uses mesibo UI modules for various functionalities like welcome screen, login, media picker, one-to-one and group messaging, user list, group management, showing profiles, etc.

Source Code of mesibo UI modules

You can also access the complete source code of UI modules here:

mesibo Messaging UI module for Android uses Google Map SDK for location. Hence, you’ll need to get your own Google Map Key to use location features. Refer to mesibo installation instruction for your platform to learn more.

In the following sections, we will explain how you can launch mesibo UI modules for messaging and calls. The code examples are taken from source code available on GitHub - First mesibo App for Android

Launching Messaging UI in Android

  1. Install mesibo UI Modules by following Instructions for Android

  2. Import the messaging-UI Module.
    import com.mesibo.messaging.MesiboUI;
    
  3. In the case of one-to-one messaging, you will need to launch the message UI for each user. For example, if there is a user named User2, you will need to launch the messaging UI like below

<img src=”images/android-first-app-message.png” width=”300” height=”500” hspace=10/>

To launch the messaging UI for a user, you need to pass the address to that user.

Here, is an example in Java

public void onLaunchMessagingUi(View view) {
        MesiboUI.launchMessageView(this, mRemoteUser.address, 0);
}

Here, is an example in Kotlin

fun onLaunchMessagingUi(view: View?) {
        MesiboUI.launchMessageView(this, mRemoteUser!!.address, 0)
}

If you want to learn more about messaging UI modules and how you can customize them see Using mesibo Messaging UI Modules

Push Notifications and Webhooks

Your app can use push notifications to alert a user about important events. For example, when the user is offline, and there is a new message, you can display a push notification so that the user can click on it and view the message. To send push notifications, you can use FCM( Firebase Cloud Messaging) or APN(Apple Push Notification). You can send all types of push notifications — background push notifications(silent notifications) and alerts through mesibo. All you need to do is configure your FCM/APN push credentials in the console. Then, mesibo will automatically send push notifications to your users on behalf of you.

You can learn more about using Push Notifications with mesibo here.

A WebHook is an HTTP(S) URL that will be invoked with POST data in real-time by mesibo when something happens; for example, an offline message, a user comes online or goes offline, etc. You can learn more about using webhooks with mesibo here.

First mesibo Application: iOS >>

mesibo, android