In this little tutorial we will discover new features of version 3.1.0 compared to previous versions and we will see a practical example through a basic android application.

VIDEO DEMO


For MQTT chat version 3.1.0, the major change consists in separating the authentication process from the connection process to the server. Therefore developer can do a single authentication to MQTT chat ideally when the user is authenticating his application in LoginActivity. Then every time the user launches the application, developer only has to connect the user to MQTT chat in a SplashActivity for example. (see figure below).

mqtt chat android lounch flow

Also we have re-implemented feature which allows to launch a chat window from a click on a button or any event without launching the chat interface.

We will start this tutorial by reminding you of how to integrate MQTT chat into any android application from API 16.

1- Integration

In the top level (project level) build.gradle file add MQTT chat Artifactory repository to the list of maven repositories like below:


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

Then in the main application build.gradle file, add MQTT chat artifacts as a dependencies like below:


android {
  compileSdkVersion 30
  defaultConfig {    
    multiDexEnabled true  
  }
}

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

It should be noted that it is necessary to set multiDexEnabled to true and to choose compileSdkVersion greater or equal to 30.

That's all for the integration, we are now going to initialize MQTT chat library in the Application class of our application.

2- Initialisation

In Application class of your android app add the following code to init MQTT hat: You get your own APP_ID and APP_SECRET after registration to admin Panel.


public class mApplication extends MultiDexApplication {

    @Override
    public void onCreate() {

        super.onCreate();       

        new Mqttchat.getBuilder()
                .context(this.getApplicationContext())
                .appName(getApplicationContext().getResources().getString(R.string.app_name))
                .appIcon(R.mipmap.ic_notification)
                .domain("mqtt-chat.com")
                .appId("mqttchat-xxxxxxx")
                .appSecret("xxxxxxxxxxxxxxxxxxxxxxxxx")
                .debugMode(true)
                .useFriends(false)
                .build();

        pictureDisk plugin=(pictureDisk) Mqttchat.getmInstance().getPluginByName(pluginA.pictures_disk);
        plugin.setMAX_PHOTO_SIZE(2);
 }
}

When initializing MQTT chat, we also specified the max photo size to 2 M for the pictures_disk plugin (see documentation)

3- Log In

logIn() function only allows you to save the user id in a file in order to be able to retrieve it later each time the application is started. To replace current user with another one, you simply have to log out current user using logOut() function and log in another user using logIn() function.

Ideally logIn() function is called after user authentication success. for example in LoginActivity like this.


public class LoginActivity extends Activity {

    @Override
    public void onCreate() {
      super.onCreate(savedInstanceState);
      /* ... */
    }

     private void logIn(){
     
      /* ... app log in process */

      Mqttchat.getmInstance().logIn(getApplicationContext(), userId, new Callback() {
                 @Override
                 public void OK(Object o) {
                      Mqttchat.getmInstance().Connect(new Callback() {
                            @Override
                            public void OK(Object o) {
                                finish();
                                Intent myIntent = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(myIntent);
                            }
                            @Override
                            public void KO(String s) {
                            }
                 }
                 @Override
                 public void KO(String s) {
                 }
     }
}

Note that in LoginActivity we used the logIn() function to log in user then just after log in successful, we called Connect() function which we will see just after. This is because we have integrated chat interface into MainActivity and therefore before launching MainActivity user must be connected to MQTT chat.

When launching application next time LoginActivity will not be called and the Connect() function must be implemented elsewhere for example in a SplashActivty.

4- Connect

Connect() function must be called before launching activity that contains MqttchatFragment. If not the following error is displayed.

mqtt chat android not connected

So, ideally it should be called when starting your application for example in a SplashActivity as follows:

    
public class SplashActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LOW_PROFILE
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_IMMERSIVE
                        );
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
    }
    setContentView(R.layout.activity_splash);
    start();
}

 private void start(){
        if(Mqttchat.getmInstance().getLoggedUser().isLogged()){
                Mqttchat.getmInstance().Connect(new Callback() {
                    @Override
                    public void OK(Object o) {
                      Intent myIntent = new Intent(SplashActivity.this,MainActivity.class);
                      startActivity(myIntent);
                      overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                      finish();
                    }
                    @Override
                    public void KO(String error) {
                      finish();
                    }
                });
        } 

}

5- Show chat GUI

Once the user is connected to MQTT chat you can then display chat interface by embedding MqttchatFragment into MainActivity or even into another fragment. To do this:

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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    
    <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 MainActivity, affect MqttchatFragment to FrameLayout component.


public class MainActivity extends PresenceActivityA {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);
        if(savedInstanceState==null){
        getSupportFragmentManager().beginTransaction().add(R.id.mqttchatFragment,MqttchatFragment.newInstance(), "mqttchat").commit();
        }
    }    
}

6- Start Chat with userid

Sometimes you need to launch chat window directly from your application when for example a user is viewing another user's profile. Without of cource displaying the main chat interface. This is possible using startChatWith() function. User must of course be connected to MQTT chat.


Button startChatWithUserId=(Button) findViewById(R.id.startChatWithUserId);
startChatWithUserId.setOnClickListener(new View.OnClickListener(){
           @Override
           public void onClick(View view) {
              try{
                   Mqttchat.getmInstance().startChatWith(MainActivity.this, userId, new Callback() {
                       @Override
                       public void OK(Object o) {
                       }

                       @Override
                       public void KO(String s) {
                        Toast.makeText(getApplicationContext(), "MQTTCHAT error: " + s, Toast.LENGTH_LONG).show();
                       }
                   });
               }catch(Exception ex){
                 Toast.makeText(getApplicationContext(),"MQTTCHAT error: "+ex.getMessage(), Toast.LENGTH_LONG).show();
               }
           }
       });

7- Log Out

This function is used when user log out from your application. For example:


Button  logOut=(Button) findViewById(R.id.logout);
logOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Mqttchat.getmInstance().logOut(new Callback() {
                    @Override
                    public void OK(Object o) {
                      Intent i = new Intent(getApplicationContext(), LoginActivity.class);
                      startActivity(i);
                      finish();
                    }
                    @Override
                    public void KO(String s) {
                       Toast.makeText(getApplicationContext(),"MQTTCHAT logOut error: "+s, Toast.LENGTH_LONG).show();
                    }
                });
            }
});

8- Disable offline notification

For version 3.1.0 user can enable or disable FCM android notifications.

mqtt chat android not connected

9- Advertising integration

We have started adding ads to MQTT chat by adding a custom view to the users fragment. For that and in Application class add the following code:


  public class mApplication extends MultiDexApplication {

    @Override
    public void onCreate() {
        super.onCreate();

        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });

        AdView adView = new AdView(this);
        adView.setAdSize(AdSize.BANNER);
        adView.setAdUnitId("ca-app-pub-xxxxxxxxxxxxx/xxxxxxxxxxx");

        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);

        Mqttchat.getmInstance().getmAdsManager().addToUsersFragment(adView);
    }
}

mqtt chat android ads

That's it for this tutorial. I hope that through a practical example MQTT CHAT android library v3.1.0 integration is clear.

Do not forget to minimize the size of your android application before publishing it to Google Play. Please read Decreasing Application size documentation section. If you are facing any issue in this tutorial, please comment in below discussions.