Home > Developers > Documentation > MQTTCHAT Android Library

MQTTCHAT Android Library Version 1.0.2

MQTTCHAT Android is an android library that provides full chat functionality and can be integrated into any android application from API 14.

1. Add MQTTCHAT Artifactory repository to the list of Maven repositories in your top level build.gradle file:

 
allprojects {
    repositories {       
        maven {
            url "http://mqttchat.telifoun.com:8081/artifactory/libs-release-local"
            credentials {
                username = "mqttchat"
                password = "telifoun"
            }
        }
    }
}   
                    

2. You can then simply add MQTTCHAT artifacts as a dependencies in the build.gradle file of your main project:


dependencies {
    implementation 'com.telifoun.mqttchat:mqttchat-core:1.0.2'
    implementation 'com.telifoun.mqttchat:mqttchat-gui:1.0.2'
}  

In Application class of your Android App add the following code to init MQTTCHAT: You can get your own App_Id and App_Secret after registration to MQTTCHAT.

        
     new Mqttchat.getBuilder()
             .context(this.getApplicationContext())
             .appName("Application Name")
             .appIcon(R.drawable.ic_launcher)
             .domain("your_domain.com")
             .appId(App_Id)
             .appSecret(App_Secret)
             .showBackButton(true)
             .debugMode(true)             
             .build();
                

Below all possible parameters for initializing MQTTCHAT.

ParameterDescriptionNote
*contextApplication context Mandatory
*domainApplication domain Mandatory
*appIdMQTTCHAT APP_IDMandatory
*appSecretMQTTCHAT APP_SecretMandatory
useFriendsEnable or not useFriends optionOptional
mqttServerMqtt Server IPOptional
mqttPortMqtt Port Optional
idleTimeoutIdle timeout to go to away statusOptional
AppNameApplication NameOptional
AppIconApplication IconOptional
debugModeEnable or not debug mode to show trace in logcatOptional
showBackButtonShow or not back button in main GUI.Optional

Login user

Before you can display any chat interface in your application you must first login your user to MQTTCHAT to do this, In your LoginActivity and just after user login success to your application, You can connect him to MQTTCHAT using logIn function.
userId is the primary field value of your users table in application database.

  
  Mqttchat.getmInstance().logIn(getApplication(), userId, new Callback() {
   @Override
   public void OK(Object o) {
   }
   @Override
   public void KO(String s) {
   }
   });

You can then check whether a user is logged to MQTTCHAT or not using this code.

  
  Mqttchat.getmInstance().getLoggedUser().isLogged();

Show Chat GUIs

Once the user is connected to MQTTCHAT you can display the chat interface by choosing the option that suits you:

1. Launch a separate chat Activity

The easiest and fastest way to display chat GUI to the user is to start chat as separate Activity, when for example the client clicks on a button or a menu icon.

  
 Mqttchat.getmInstance().lounchMqttChat(getApplicationContext(), new Callback() {
   @Override
   public void OK(Object o) {
   }
   @Override
   public void KO(String s) {   
   }
});

2. Integrate chat as a Fragment

In some cases, developers want to integrate chat as a fragment to embed it into the main activity or even into another fragment. This allows more flexibility and consistency in the design of the application. We have offered this possibility with the greatest possible ease.

First add FrameLayout component to MainActivity layout (activity_layout.xml).


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<FrameLayout
android:name="com.telifoun.mqttchat.gui.MqttchatFragment"
android:id="@+id/mqttchatFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</LinearLayout> 

Then in the oncreate method of your main activity, affect MqttchatFragment to FrameLayout component.

  
   public class MainActivity extends PresenceActivityA {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);
        getSupportFragmentManager().beginTransaction().add(R.id.mqttchatFragment,MqttchatFragment.newInstance(), "mqttchat").commit();
    }    
}

Every activity used in your application should extends abstract class PresenceActivityA to keep presence system running in all activities of you Application. Except for activities called when user is not yet logged to MQTTCHAT like Register or login Activities.
Be carefull: Extending PresenceActivityA for activities when user is not logged to Mqttchat will raise error.

Below screenshots of Android chat application CHATI that use MqttchatFragment published recently in google play.



3. Open a chat window with a specific user

MQTTCHAT also allows you to open a chat window directly from your application when for example a user is viewing the profile of another user and wants to start a chat with him. You can then directly display the chat window by clicking on a button.

  
    Mqttchat.getmInstance().openChatWindowWith(MainActivity.this, toUserId, new Callback() {
    @Override
    public void OK(Object o) {}
    @Override
    public void KO(String error) {}                    
  });

LogOut user

This function is normally used when user disconnect from your application.

  
   Mqttchat.getmInstance().logOut(new Callback() {
  @Override
   public void OK(Object o) {
   }
   @Override
   public void KO(String s) {   
   }
});

You can capture all MQTT CHAT events using a mqttchatListener :

  
mqttchatListener listener= new mqttchatListener() {
            @Override
            public void onLoadComplete() {
              Log.i(Tag,"MQTT Chat load complete");
            }

            @Override
            public void onUserPresenceUpdate(int i, String s, boolean b, boolean b1, String s1) {
             Log.i(Tag,"User presence update : userId:"+i +"; new status:"+s+" ;voice capacity:"+b +" ;video capacity:"+b1+"; timestamp:"+s1);
            }

            @Override
            public void onSendMessage(int i, Message message) {
                Log.i(Tag,"Logged user send message to userId :"+i +"; message:"+message.toString());
            }

            @Override
            public void onAckMessage(int i, Ack ack, Message message) {
                Log.i(Tag,"Logged user received Ack from server for message sent to userId :"+i +"; ack :"+ack.toString()+"; message:"+message.toString());
            }

            @Override
            public void onRejectMessage(int i, String s, Message message) {
                Log.i(Tag,"Logged user has sent message to userId:"+i+"; message was rejected by server because of :"+s+"; and message content :"+message.toString());
            }

            @Override
            public void onIncomingMessage(int i, Message message) {
                Log.i(Tag,"Logged user received new message from userId:"+i+"; message content:"+message.toString());
            }

            @Override
            public void onUserTyping(int i, boolean b) {
                Log.i(Tag,"A user  userId:"+i+" is currently typing to logged user; is typing :"+b);
            }

            @Override
            public void onReadingMessage(int i, int i1, String s) {
                Log.i(Tag,"A user userId:"+i+"; is reading message id:"+i1+" ; reading date :"+s);
            }

            @Override
            public void onNotReadMessagesCountUpdate(int i) {
                Log.i(Tag,"Number of unread messages is changed for logged user, new number is :"+i);
            }

            @Override
            public void onError(int i, String s) {
                Log.e(Tag,"MQTTCHAT error code :"+i+";message :"+s);
            }
       };

       /** add new MQTTCHAT listener **/
       Mqttchat.getmInstance().addMqttchatListener(listener);

       /** remove MQTTCHAT listener **/
       Mqttchat.getmInstance().removeMqttchatListener(listener);  

MQTTCHAT android application contains 6 plugins by default: smileys, stickers, pictures from DISK, pictures from CAM, records and Visio Notifications.

Simleys

Is used to send smileys.

Stickers

Is used to send some Stickers, you can catch sticker sending event using stickersListener.

   
Stickers plugin=(Stickers) Mqttchat.getmInstance().getPluginByName(pluginA.stickers);
        plugin.setListener(new stickersListener() {
            @Override
            public void onMqttchatSendSticker(int toUserId,String stickerCode) {
               // your custom code here 
            }
        });

Send Picture from DISK

Is used to send pictures from local Disk, you can catch picture sending event using pictureDiskListener.

   
pictureDisk plugin=(pictureDisk) Mqttchat.getmInstance().getPluginByName(pluginA.pictures_disk);
        plugin.setPictureDiskListener(new pictureDiskListener() {
            @Override
            public void onMqttchatSendPictureDisk(int toUserId,String urlMin,String urlMax) {
              //your custom code here  
            }
        });

You can also adjust some plugin parameters:

ParameterDescriptionDefault value
MAX_PHOTOS_TO_DROPmaximum number of photos to be sent simultaneously6
MAX_PHOTO_SIZESingle photo max size1 Mo
 
plugin.setMAX_PHOTOS_TO_DROP(3);
plugin.setMAX_PHOTO_SIZE(2);

Send Picture from Camera

Is used to send pictures from Camera, you can catch picture sending event using pictureCamListener.

   
pictureCam plugin=(pictureCam) Mqttchat.getmInstance().getPluginByName(pluginA.pictures_cam);
        plugin.setPictureCamListener(new pictureCamListener() {
            @Override
            public void onMqttchatSendPictureCam(int toUserId,String urlMin,String url) {
              //your custom code here  
            }
        });

You can also adjust some plugin parameters:

ParameterDescriptionDefault value
MAX_PHOTOS_TO_DROPmaximum number of photos to be sent simultaneously3
 
plugin.setMAX_PHOTOS_TO_DROP(1);

Send Voice Notes

Is used to send voice notes, you can catch voice notes sending event using recordsListener.

   
records plugin=(records) Mqttchat.getmInstance().getPluginByName(pluginA.records);
        plugin.setRecordsListener(new recordsListener() {
            @Override
            public void onMqttchatSendRecord(int toUserid,String duration,String Url){
             //your custom code here   
            }
        });

You can also adjust some plugin parameters:

ParameterDescriptionDefault value
RECORD_TIME_LIMITmaximum recording time of one single record1 min
 
plugin.setRECORD_TIME_LIMIT(1);

Visio Notifications

Is used for missed and completed calls notifications.

FCM Notifications

FCM (Firebase Cloud Messaging) is a free service from Google that lets users reliably deliver push notifications to web or android devices.

For more information on FCM please see the following documentation:

MQTTCHAT uses FCM for two purposes:
  • + Send notifications when messages are received and the android application is closed.
  • + Route audio and video calls when the application is closed.

FCM functionality is not activated by default, to activate it for your application, you must follow the following steps:

Step1.

First you need to setup your app to firebase console to get a google-serivces.json file. Then you need to add this file to your project under app package.

Once the json file is added you need to add the Firebase dependencies.

In the project's build.gradle:

         
   buildscript {
    dependencies {
     // Add this line
     classpath 'com.google.gms:google-services:4.3.3'
    }
   }     

And at the bottom of the app's build.gradle add:

         
apply plugin: 'com.google.gms.google-services'

That is all. MQTTCHAT takes care of others configs and use of FCM in source code.

Step2.

Now you need to add your FCM server key to your MQTTCHAT client area to allow our MQTT servers to send notifications to your users' devices.

You can get the server key from the FCM firebase console/project/settings/cloud Messaging/server key.

13 STEPS

1 The first step is to open Solution de chat avec MQTT - MQTTCHAT and click fr

Step 1 image

2 Click English

Step 2 image

3 Click Client Area

Step 3 image

4 Click test123.com

Step 4 image

5 Click Settings

Step 5 image

6 Click SETTINGS

Step 6 image

7 Scroll down and click Off

Step 7 image

8 Click Please enter the FCM server key then click on t...

Step 8 image

9 Click content_copy

Step 9 image

10 Click Please enter the FCM server key then click on t...

Step 10 image

11 Press shortcut - Ctrl + v

Step 11 image

12 Click highlight

Step 12 image

13 Scroll up and that's it. You're done.

Step 13 image

Here's an interactive tutorial for the visual learners

https://www.iorad.com/player/1656408/Mqttchat-Telifoun---How-to-untitled-task-name



Users presence status

MQTTCHAT allows you to retrieve your domain users presence status in real time through the use of a Callback URL. You can then save user's presence status in your android application and then show list of online users or filter users by presence status.
The feature is not enabled by default, to activate it you must define a valid Callback URL and enable the option from your MQTTCHAT client area.
Once the option is activated, for each change of user presence status, our MQTT servers send to this URL three variables: :

userid : user id.
status : new presence status of user.
timestamp : unix timestamp of the last presence status.

Below is an example of a PHP page https://www.votre-domain.com/callback.php that retrieves and displays parameters sent by MQTTCHAT.

 
        /* get userid  */
        echo $_REQUEST["userid"];

        /* get new status */
        echo $_REQUEST["status"];

        /* get status unix timestmp */
        echo $_REQUEST["timestamp"];
        

7 STEPS

1 The first step is to open Chat solution for 1$ only, self hosted or cloud... and click Client Area

Step 1 image

2 Click test123.com

Step 2 image

3 Click Settings

Step 3 image

4 Click SETTINGS

Step 4 image

5 Click Off

Step 5 image

6 Click highlight

Step 6 image

7 That's it. You're done.

Step 7 image

Here's an interactive tutorial for the visual learners

https://www.iorad.com/player/1656425/Mqttchat-Telifoun---How-to-untitled-task-name



Custom colors

You can customize Mqttchat GUI colors to match your android application theme.

Below differents color variables used by MQTTCHAT

Color nameColor
mqttchat_colorPrimary
mqttchat_colorPrimaryDark
mqttchat_colorAccent
mqttchat_textColorPrimary
mqttchat_textColor
mqttchat_tabtextActiveColor
mqttchat_tabtextColor
mqttchat_windowBackgroundColor
mqttchat_sendMessageBoxBackgroundColor
mqttchat_contactNameColor
mqttchat_pluginsToolbarColor
mqttchat_contactLastMessageNormalColor
mqttchat_contactLastMessageNotReadColor
mqttchat_listviewBackgroundIdleColor
mqttchat_listviewBackgroundPressedColor
mqttchat_contactNotReadMessagesCountBackgroundColor
mqttchat_contactNotReadMessagesCountColor

To edit a color to match your application theme, you need to overrite the value of color variable in your app color.xml ressource file.

 
   <resources>
        
   <color name="colorPrimary">#008577</color>
   <color name="colorPrimaryDark">#00574B</color>
   <color name="colorAccent">#008577</color>
   
   <color name="mqttchat_colorPrimary">#008577</color>
   <color name="mqttchat_colorAccent">#008577</color>
   <color name="mqttchat_textColorPrimary">#FFFFFF</color>
   <color name="mqttchat_pluginsToolbarColor">#008577</color>
    
 </resources>
  


Custom module

An MQTTCHAT module allows you to integrate custom actions in the dropdown menu of chat window. Such as displaying the profile of user with whom a connected user is chatting or any action related to the opened chat window.

To create a custom MQTTCHAT module, you need to add java class that extends moduleA abstract class.

For example the module below allows to display the profile of the user corresponding to the current discussion by clicking on the menu.


        public class userProfile extends com.telifoun.mqttchat.modules.moduleA {
            /**
             *
             * @param ctx
             * @param Name
             * @param Label
             */
            public userProfile(android.content.Context ctx, String Name, String Label) {
                super(ctx, Name, Label);
            }    
            @Override
            public void moduleMenuItemCLicked() {
                /* lounch profile activity on menu item click */
                Intent i = new Intent(getMessageActivity(), ProfileActivity.class);
                i.putExtra("userId", getMessageActivity().getToUserid());
                getMessageActivity().startActivity(i);
            }
        }

        

Then Add module to MQTTCHAT in Application class.


        userProfile mProfile=new userProfile(getApplicationContext(),"User Profile","Go to Profile");
        Mqttchat.getmInstance().getModules().add(mProfile);
        


Custom plugin

Unlike an MQTTCHAT module, the plugin allows you to send new content or new message type between users, like basic plugins provided by MQTTCHAT (smileys, stickers, records ...)

First add plugin class that extends pluginA abstract class to your App

 
              public class samplePlugin extends com.telifoun.mqttchat.plugins.pluginA {

                private Context mContext;
                private  LinearLayout view;

                /**
                 *
                 * @param ctx
                 * @param Name
                 * @param Label
                 * @param useIcon
                 * @param idleIconId
                 * @param pressedIconId
                 */
                public samplePlugin(android.content.Context ctx, String Name, String Label, boolean useIcon, int idleIconId, int pressedIconId) {
                    super(ctx, Name, Label, useIcon, idleIconId, pressedIconId);
                    mContext=ctx;
                }

                @Override
                public void init() {
                    view = new LinearLayout(mContext);
                    view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                    view.setOrientation(LinearLayout.HORIZONTAL);
                    TextView iv = new TextView(mContext);
                    iv.setText("Plugin Gui here");
                    view.addView(iv);     
                }

                @Override
                public View getRootView() {
                    return view;
                }  

                /**
                 * function that render plugin item in messages listview
                 * @param linearLayout
                 * @param view
                 * @param message
                 * @return
                 */     
                @Override
                public View render(LinearLayout linearLayout, View view, Message message) {
                    if(view==null){
                        LayoutInflater mInflater = (LayoutInflater) linearLayout.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        view = mInflater.inflate(R.layout.render_plugin, linearLayout, false);
                    }
                    LinearLayout pluginLayout=(LinearLayout) view.findViewById(R.id.pluginLayout);
                    TextView txt =(TextView) view.findViewById(R.id.renderItemText) ;
                    this.setAlignment(pluginLayout,message.getFrom());
                    txt.setText(message.getMessage().toString());
                    return view;
                 }

                /**
                 * function that add text to last message send in contacts listview
                 * @param i
                 * @param message
                 * @return
                 */
                @Override
                public SpannableStringBuilder preview(int i, Message message) {
                    SpannableStringBuilder builder = new SpannableStringBuilder();
                    if(message.getFrom()== Mqttchat.getmInstance().getLoggedUser().getUserId()){ //out message
                        builder.append("Outbox plugin message ");
                    }else{
                        builder.append("Inbox plugin message ");
                    }
                    return builder;       
                }   
                /**
                 * function called when user select plugin (plugin oppened) and click in send button
                 */
                @Override
                public void onSendMessageButtonCLicked() {      
                  this.sendMessage("plugin text message to Send", new Callback() {
                      @Override
                      public void OK(Object o) {
                          getMessageActivity().requestMessageBtnOff(getName());
                      }
                      @Override
                      public void KO(String s) {
                          getMessageActivity().requestMessageBtnOff(getName());
                          onError(s);
                      }
                  });
                }
            }
            

Then Add plugin to MQTT CHAT in Application class.

    
            samplePlugin p =new samplePlugin(getApplicationContext(),
                            "SamplePlugin",
                            "Sample Plugin",
                            true,
                            R.drawable.ic_share_off,
                            R.drawable.ic_share_on);
            Mqttchat.getmInstance().getPlugins().add(p);
            

If you want a specific plugin that requires advanced integration with MQTTCHAT. please contact us and specify your needs.

When an APK is downloaded by a user, unused code and data is also downloaded. This isn’t ideal, but most Android developers are doing it this way since it’s the default. Fortunately, the Google Developer API is robust and allows for multiple APK support if you want to target specific devices with slimmed down APKs.

 

ext.abiCodes = ['armeabi-v7a': 1, 'arm64-v8a': 2, 'x86': 3, 'x86_64': 4]

import com.android.build.OutputFile

// For each APK output variant, override versionCode with a combination of
// ext.abiCodes * 1000 + variant.versionCode. In this example, variant.versionCode
// is equal to defaultConfig.versionCode. If you configure product flavors that
// define their own versionCode, variant.versionCode uses that value instead.
android.applicationVariants.all { variant ->

    // Assigns a different version code for each output APK
    // other than the universal APK.
    variant.outputs.each { output ->

        // Stores the value of ext.abiCodes that is associated with the ABI for this variant.
        def baseAbiVersionCode =
                // Determines the ABI for this variant and returns the mapped value.
                project.ext.abiCodes.get(output.getFilter(OutputFile.ABI))

        // Because abiCodes.get() returns null for ABIs that are not mapped by ext.abiCodes,
        // the following code does not override the version code for universal APKs.
        // However, because we want universal APKs to have the lowest version code,
        // this outcome is desirable.
        if (baseAbiVersionCode != null) {

            // Assigns the new version code to versionCodeOverride, which changes the version code
            // for only the output APK, not for the variant itself. Skipping this step simply
            // causes Gradle to use the value of variant.versionCode for the APK.
            output.versionCodeOverride =
                    baseAbiVersionCode * 1000 + variant.versionCode
        }
    }
}
           

It is highly recommended to add this code to the end of the build.gradle file of your main project. This code tells to Gradle to generate multiple APKs by ABI type during a release build. And therefore the size of your application will be much smaller.

See MQTTCHAT github demo Application : mqttchat-android-demo

Try it on google play store :

2020 © Telifoun.MQTTCHAT Inc.