Write your First mesibo Enabled Application - Android

Estimated reading time: 21 minutes

In this part, we will create a simple real-time app for Android.

The app will allow you to log in as two different users so that you can try various mesibo features. We will cover the following in this part.

Please go through the following prerequisites before you read further.

Prerequisites and Download Source Code

  • 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.
  • [Optional] You can download and run mesibo messenger app on one of your phones so that you can use it to test the First App.

Configure and Build First Android App

In this step, we will configure and build the First App. Once you run it, we will get into more details.

Step 1 Open Project

Start Android Studio and open the project that you downloaded from GitHub.

This project already has all the mesibo SDKs configured. However, in the future, if you are creating a new project, you can add mesibo SDKs to your project by adding Gradle dependency and performing Gradle sync as explained in installation instructions.

Step 2 Configure Mesibo Tokens

Before we can build and run the app, we need to configure app with valid mesibo user tokens as explained in Create Users section.

Create tokens for two users, each with the User Address 123 and 456 and App ID com.mesibo.firstapp and configure two demo users in the source code with the tokens you have generated.

For example, in Java

DemoUser mUser1 = new DemoUser("<token 1>", "User-1", "123");
DemoUser mUser2 = new DemoUser("<token 2>", "User-2", "456");

Example, in Kotlin

internal var mUser1 = DemoUser("<token 1>", "User-1", "123")
internal var mUser2 = DemoUser("<token-2>", "User-2", "456")

Step 3 Build and Run

Build and Run the project. It may take a few seconds and then you should see the following screen

You should install the app on two devices. On the first device, click on the Login as User1 button and on another device, click on the Login as User2 button.

If you add a breakpoint on Mesibo_OnConnectionStatus, you will see that it cycles 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.

You can now send messages to each other and can also make voice and video calls.

If you check the logs or add a breakpoint on Mesibo_OnMessage, you can see that you got the message in Mesibo_OnMessage listener.

Once you have tried all the demo features, you can start going into details below.

Code Explanation

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

Note that, except addListener, all other initialization functions should be only called once.

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.

Getting a User Profile

Mesibo has a profile for every valid user and group in your app. You can get a profile for any user by calling getProfile API. Here we will get a profile for our remote user.

In Java,

mProfile = Mesibo.getProfile(address);

In Kotlin,

mProfile = Mesibo.getProfile(address)

Once you have the profile, you can perform various APIs like accessing profile information (name, picture, ..), sending messages, etc.

Sending and Receiving Messages

Now we will quickly learn how to send messages in real-time.

Sending messages are very simple. you only need to call sendMessage real-time API of the profile to which you need to send message. In our case, we have obtained profile using getProfile API above. 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) {
    // profile that we obtained using getProfile() API earlier
    mProfile.sendMessage(Mesibo.random(), mMessage.getText().toString().trim());
}

In Kotlin,

fun onSendMessage(view: View?) {
    // profile that we obtained using getProfile() API earlier
    mProfile?.sendMessage(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 charge any additional amount for the voice or video call APIs.

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.

Video and Voice Call APIs

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

Group messaging is no different from the one-to-one messaging. You can invoke the same messaging APIs to send a group message, instead of the user’s profile, you need to use group profile.

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, but instead of using the user profile, you first get the group profile using the group-id and use it to send group message.

Using Java,

profile = Mesibo.getProfile(96568);
profile.sendMessage(Mesibo.random(), message);

Using Kotlin,

profile = Mesibo.getProfile(96568);
profile?.sendMessage(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.

Creating a Group

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 add/remove members by using backend APIs and mesibo console if requires.

You can create a new group by calling createGroup API, with name and the Group Listener Object.

In Java,

Mesibo.createGroup("My Group", 0, this);

In Kotlin

Mesibo.createGroup("My Group", 0, this);

It will send a request to the server to create a new group. When a group is created, callback function in the listener will be called with the group profile. You can then add members to the group using group profile APIs.

@Override
public void Mesibo_onGroupCreated(MesiboProfile profile) {
	Log.d(TAG, "New group " + groupProfile.groupid);
}

You can now use this new group profile for messaging, adding more members or changing group name, description, picture, etc.

Adding members to a Group

You can add members, and admins to the group by calling addMembers API of the group profile. You need to pass the addresses of the users to be added as group members, permissions to be granted and admin permissions if you are adding them as group admins.

For example,

String[] members = {"18005550001", "18005550002", "18005550003"};
MesiboGroupProfile gp = profile.getGroupProfile();
gp.getGroupProfile().addMembers(members, MESIBO_MEMBERFLAG_ALL, 0);

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 or 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 = profile.createReadSession(this);
mReadSession.enableReadReceipt(true);
mReadSession.read(100);

To read the last message from each user and group (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 or a group, in Kotlin

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

To read last message from each user and group (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

messaging

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