Sunday 5 March 2017

Android MQTT


This Blog has been migrated tohttps://medium.com/@gaikwadchetan93/android-real-time-communication-using-mqtt-9ea42551475d

MQTT
(Message Queue Telemetry Transport)

What is MQTT?
MQTT is a machine-to-machine (M2M)/"Internet of Things" connectivity protocol.

Used for simple communication between multiple devices with a simple messaging protocol in RealTime.

Some of the related concepts
    -Pub-Sub: publish-subscribe-based messaging protocol.
    -Broker: The broker is responsible for distributing messages to interested clients based on the topic of a message.


Some of the broker server tasks are
  -Receive all messages
  -Filter  and rectify the interesting subscriber
  -send/publish msg to all  subscriber
  
     -TopicA topic is a UTF-8 string, which is used by the broker to filter messages for each connected client. A topic consists of one or more topic levels. Each topic level is separated by a forward slash. eg:global/demo



Why not HTTP for this purpose?
-No Good solution for push and Quality of service
-Require more bandwidth
-Acting as host require more battery(To listen for incoming request and server)
-more battery

MQTT advantages
-Pub-Sub protocol
-Limited Bandwidth - It is designed for connections to remote locations where a "small code footprint" is required or the network bandwidth is limited
-Binary format requires less bandwidth
-Less battery





Lets jump into code how to implement MQTT in Android

Installation

To add the Paho Android Service as a dependency to you app add the following parts to your gradle file.
repositories {
    maven {
        url"https://repo.eclipse.org/content/repositories/paho-releases/"
   
}
}


dependencies {
compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'

compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.0'
}


In you manifiest file add below tag under <application>
<service android:name="org.eclipse.paho.android.service.MqttService"></service>

Add following permission




<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />


Initialize

String clientId = MqttClient.generateClientId();
MqttAndroidClient client = new MqttAndroidClient(application, "BROKER SERVER",
        clientId);

1. Connect

void connectToMqtt(final MqttAndroidClient client) {
    try {
        IMqttToken token = client.connect();
        token.setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
              // We are connected
               Timber.d("On Mqtt connect success");
               subscribeToMqttChannel(client);
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
              // Something went wrong e.g. connection timeout or firewall problems 
               Timber.d("On Mqtt connect failure %s",exception.getMessage());

            }
        });
    } catch (MqttException e) {
        e.printStackTrace();
    }
}
 
2. Subscribe



void subscribeToMqttChannel(MqttAndroidClient client) {

    String topic = "demo";

    int qos = 1;

    try {

        IMqttToken subToken = client.subscribe(topic, qos, iMqttMessageListener);



    } catch (MqttException e) {

        e.printStackTrace();

    }

}



IMqttMessageListener iMqttMessageListener = new IMqttMessageListener() {

    @Override

    public void messageArrived(String topic, MqttMessage message) throws Exception {

        Timber.d("Message received %s",message);

        JSONObject signallStatus = new JSONObject(message.toString());



    }

};





 
3. UnSubscribe

void unSubscribeMqttChannel(MqttAndroidClient client) {

    final String topic = "demo";

    try {

        IMqttToken unsubToken = client.unsubscribe(topic);

        unsubToken.setActionCallback(new IMqttActionListener() {

            @Override

            public void onSuccess(IMqttToken asyncActionToken) {

                // The subscription could successfully be removed from the client

                Timber.d("On Mqtt unSubscribed");

            }



            @Override

            public void onFailure(IMqttToken asyncActionToken,

                                  Throwable exception) {

                // some error occurred, this is very unlikely as even if the client

                // did not had a subscription to the topic the unsubscribe action

                // will be successfully

                Timber.d("On Mqtt unSubscribe failure %s",exception.getMessage());

            }

        });

    } catch (MqttException e) {

        e.printStackTrace();

    }

}



4.Disconnect

void disconnectMqtt(MqttAndroidClient client) {

    try {

        IMqttToken token = client.disconnect();

        token.setActionCallback(new IMqttActionListener() {

            @Override

            public void onSuccess(IMqttToken asyncActionToken) {

                // We are connected

                Timber.d("On Mqtt disconnected");

            }



            @Override

            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {

                // Something went wrong e.g. connection timeout or firewall problems

                Timber.d("On Mqtt disconnect failure %s",exception.getMessage());



            }

        });

    } catch (MqttException e) {

        e.printStackTrace();

    }

}




Usage
Facebook Messenger. Facebook has used aspects of MQTT in Facebook Messenger for online chat.However, it is unclear how much of MQTT is used or for what.

So I think we don't need to mention more example to understand the importance of MQTT above one is enough.




Try it yourself
 
Please suggest if any update.
 
Updates are always welcome
 
HAPPY CODING :)
 
 
 
source code  https://github.com/gaikwadChetan93/Android-MQTT-Demo

My Apps MobileUtility

Wednesday 1 June 2016

Solving Memory leaks issue with custom font in Android

Today I will discuss some memory leak issue while using custom fonts in android.

Using custom fonts may leads to some serious memory leak issues so while using custom fonts you should avoid this memory leaks.

Steps to reproduce 
1. Write an application that calls Typeface.createFromAsset() multiple times.
2. Make sure that the typeface objects are out of scope and the garbage collector has completed at least one pass.
3. Run adb shell dumpsys meminfo <your app package>

For complete issue discussion please visit https://code.google.com/p/android/issues/detail?id=9904

Normally we use custom fonts as below
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/Arial.ttf");
tv.setTypeface(font);

Please a take a look on memory dumb, when custom views are used.

** MEMINFO in pid 10045 [com.android.test] **
                         Shared  Private     Heap     Heap     Heap
                   Pss    Dirty    Dirty     Size    Alloc     Free
                ------   ------   ------   ------   ------   ------
       Native        0        0        0    15596    14337     1258
       Dalvik    44483    11156    44292    64775    43074    21701
       Cursor        0        0        0                           
       Ashmem        0        0        0                           
    Other dev        4       36        0                           
     .so mmap     5380     2196     4752                           
    .jar mmap        0        0        0                           
    .apk mmap      362        0        0                           
    .ttf mmap      102        0        0                           
    .dex mmap      964        0        0                           
   Other mmap     1283      320      204                           
      Unknown     9452      528     9448                           
        TOTAL    62030    14236    58696    80371    57411    22959

 Objects
               Views:      981         ViewRootImpl:        2
         AppContexts:        4           Activities:        3
              Assets:       28        AssetManagers:       28
       Local Binders:       16        Proxy Binders:       19
    Death Recipients:        0
     OpenSSL Sockets:        1

 SQL
         MEMORY_USED:        0
  PAGECACHE_OVERFLOW:        0          MALLOC_SIZE:        0


 Asset Allocations
    zip:/data/app/com.android.test-2.apk:/resources.arsc: 135K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS.ttf: 133K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS.ttf: 133K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS.ttf: 133K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS.ttf: 133K
    zip:/data/app/com.android.test-2.apk:/assets/fonts/Trebuchet MS Bold.ttf: 123K
So instead of this we should cache the Typeface as below


public class FontCache {

    private static Hashtable<String, Typeface> fontCache = new Hashtable<String, Typeface>();

    public static Typeface get(String name, Context context) {
        Typeface tf = fontCache.get(name);
        if(tf == null) {
            try {
                tf = Typeface.createFromAsset(context.getAssets(), name);
            }
            catch (Exception e) {
                return null;
            }
            fontCache.put(name, tf);
        }
        return tf;
    }
}



Usage
Typeface tf = FontCache.get("fonts/MavenPro-Regular.ttf", this);
mTestTV.setTypeface(tf);
mTestTV.setText("Safe typeface use");


References
https://stackoverflow.com/questions/16901930/memory-leaks-with-custom-font-for-set-custom-font

https://stackoverflow.com/questions/23977114/custom-font-in-android-leaking-memory

Please try to use custom font with and without caching in a listview of some 100 items you will get the difference

Source code : https://github.com/gaikwadChetan93/SafeCustomFonts

Try it yourself
Please suggest if any update.
Updates are always welcome
HAPPY CODING :)

My Apps MobileUtility