androidX org.eclipse.paho.android.service:报错Program type already present

报错原因

项目升级至Android X环境下面这个包不支持

implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.0.2'

对应的另一个包却支持AndroidX环境,无须修改

implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'

解决方案

  • 源码导入项目,适配源码到AndroidX环境,官方未适配,只能自己适配
  • 记得修改新的MqttService路径
  • 同时记得删除官方依赖org.eclipse.paho:org.eclipse.paho.android.service:1.0.2

解决方案二


-我已经帮你改好该包并适配Android X
-你只需要逐个新建以下几个类到项目某个文件夹下面即可
在这里插入图片描述

  • AndroidManifest
<service android:name="com.iot.listeninsoul.service.MqttService" />
  • 同时记得删除官方依赖org.eclipse.paho:org.eclipse.paho.android.service:1.0.2
  • 但保留另一个库org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2

AlarmPingSender.java

package com.iot.listeninsoul.service;


import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.PowerManager;
import android.util.Log;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttPingSender;
import org.eclipse.paho.client.mqttv3.internal.ClientComms;

/**
 * Default ping sender implementation on Android. It is based on AlarmManager.
 *
 * <p>This class implements the {@link MqttPingSender} pinger interface
 * allowing applications to send ping packet to server every keep alive interval.
 * </p>
 *
 * @see MqttPingSender
 */
public class AlarmPingSender implements MqttPingSender {
    static final String TAG = "AlarmPingSender";
    private ClientComms comms;
    private MqttService service;
    private BroadcastReceiver alarmReceiver;
    private AlarmPingSender that;
    private PendingIntent pendingIntent;
    private volatile boolean hasStarted = false;

    public AlarmPingSender(MqttService service) {
        if (service == null) {
            throw new IllegalArgumentException("Neither service nor client can be null.");
        } else {
            this.service = service;
            this.that = this;
        }
    }

    public void init(ClientComms comms) {
        this.comms = comms;
        this.alarmReceiver = new AlarmPingSender.AlarmReceiver();
    }

    public void start() {
        String action = "MqttService.pingSender." + this.comms.getClient().getClientId();
        Log.d("AlarmPingSender", "Register alarmreceiver to MqttService" + action);
        this.service.registerReceiver(this.alarmReceiver, new IntentFilter(action));
        this.pendingIntent = PendingIntent.getBroadcast(this.service, 0, new Intent(action), PendingIntent.FLAG_UPDATE_CURRENT);
        this.schedule(this.comms.getKeepAlive());
        this.hasStarted = true;
    }

    public void stop() {

        AlarmManager alarmManager = (AlarmManager)this.service.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(this.pendingIntent);
        Log.d("AlarmPingSender", "Unregister alarmreceiver to MqttService" + this.comms.getClient().getClientId());
        if (this.hasStarted) {
            this.hasStarted = false;
            try {
                this.service.unregisterReceiver(this.alarmReceiver);
            } catch (IllegalArgumentException var3) {

            }
        }

    }

    public void schedule(long delayInMilliseconds) {
        long nextAlarmInMilliseconds = System.currentTimeMillis() + delayInMilliseconds;
        Log.d("AlarmPingSender", "Schedule next alarm at " + nextAlarmInMilliseconds);
        AlarmManager alarmManager = (AlarmManager)this.service.getSystemService(Context.ALARM_SERVICE);
        if (Build.VERSION.SDK_INT >= 19) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextAlarmInMilliseconds, this.pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, nextAlarmInMilliseconds, this.pendingIntent);
        }

    }

    class AlarmReceiver extends BroadcastReceiver {
        private PowerManager.WakeLock wakelock;
        private String wakeLockTag;

        AlarmReceiver() {
            this.wakeLockTag = "MqttService.client." + AlarmPingSender.this.that.comms.getClient().getClientId();
        }

        public void onReceive(Context context, Intent intent) {
            int count;
            try {
                count = intent.getIntExtra("android.intent.extra.ALARM_COUNT", -1);
            } catch (ClassCastException var6) {
                Long longCount = intent.getLongExtra("android.intent.extra.ALARM_COUNT", -1L);
                count = longCount.intValue();
            }

            Log.d("AlarmPingSender", "Ping " + count + " times.");
            Log.d("AlarmPingSender", "Check time :" + System.currentTimeMillis());
            PowerManager pm = (PowerManager) AlarmPingSender.this.service.getSystemService(Context.POWER_SERVICE);
            this.wakelock = pm.newWakeLock(1, this.wakeLockTag);
            this.wakelock.acquire();
            IMqttToken token = AlarmPingSender.this.comms.checkForActivity(new IMqttActionListener() {
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.d("AlarmPingSender", "Success. Release lock(" + AlarmPingSender.AlarmReceiver.this.wakeLockTag + "):" + System.currentTimeMillis());
                    AlarmPingSender.AlarmReceiver.this.wakelock.release();
                }

                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.d("AlarmPingSender", "Failure. Release lock(" + AlarmPingSender.AlarmReceiver.this.wakeLockTag + "):" + System.currentTimeMillis());
                    AlarmPingSender.AlarmReceiver.this.wakelock.release();
                }
            });
            if (token == null && this.wakelock.isHeld()) {
                this.wakelock.release();
            }

        }
    }
}

DatabaseMessageStore.java

package com.iot.listeninsoul.service;

import java.util.Iterator;
import java.util.UUID;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Implementation of the {@link MessageStore} interface, using a SQLite database
 */
class DatabaseMessageStore implements MessageStore {

    private static String TAG = "DatabaseMessageStore";
    private static final String MTIMESTAMP = "mtimestamp";
    private static final String ARRIVED_MESSAGE_TABLE_NAME = "MqttArrivedMessageTable";
    private SQLiteDatabase db = null;
    private DatabaseMessageStore.MQTTDatabaseHelper mqttDb = null;
    private MqttTraceHandler traceHandler = null;

    public DatabaseMessageStore(MqttService service, Context context) {
        this.traceHandler = service;
        this.mqttDb = new DatabaseMessageStore.MQTTDatabaseHelper(this.traceHandler, context);
        this.traceHandler.traceDebug(TAG, "DatabaseMessageStore<init> complete");
    }

    public String storeArrived(String clientHandle, String topic, MqttMessage message) {

        this.db = this.mqttDb.getWritableDatabase();
        this.traceHandler.traceDebug(TAG, "storeArrived{" + clientHandle + "}, {" + message.toString() + "}");
        byte[] payload = message.getPayload();
        int qos = message.getQos();
        boolean retained = message.isRetained();
        boolean duplicate = message.isDuplicate();
        ContentValues values = new ContentValues();
        String id = UUID.randomUUID().toString();
        values.put("messageId", id);
        values.put("clientHandle", clientHandle);
        values.put("destinationName", topic);
        values.put("payload", payload);
        values.put("qos", qos);
        values.put("retained", retained);
        values.put("duplicate", duplicate);
        values.put("mtimestamp", System.currentTimeMillis());

        try {
            this.db.insertOrThrow("MqttArrivedMessageTable", (String)null, values);
        } catch (SQLException var11) {
            this.traceHandler.traceException(TAG, "onUpgrade", var11);
            throw var11;
        }

        int count = this.getArrivedRowCount(clientHandle);
        this.traceHandler.traceDebug(TAG, "storeArrived: inserted message with id of {" + id + "} - Number of messages in database for this clientHandle = " + count);
        return id;

    }

    private int getArrivedRowCount(String clientHandle) {
        int count = 0;
        String[] projection = new String[]{"messageId"};
        String selection = "clientHandle=?";
        String[] selectionArgs = new String[]{clientHandle};
        Cursor c = this.db.query("MqttArrivedMessageTable", projection, selection, selectionArgs, (String)null, (String)null, (String)null);
        if (c.moveToFirst()) {
            count = c.getInt(0);
        }

        c.close();
        return count;
    }

    public boolean discardArrived(String clientHandle, String id) {
        this.db = this.mqttDb.getWritableDatabase();
        this.traceHandler.traceDebug(TAG, "discardArrived{" + clientHandle + "}, {" + id + "}");
        String[] selectionArgs = new String[]{id, clientHandle};

        int rows;
        try {
            rows = this.db.delete("MqttArrivedMessageTable", "messageId=? AND clientHandle=?", selectionArgs);
        } catch (SQLException var6) {
            this.traceHandler.traceException(TAG, "discardArrived", var6);
            throw var6;
        }

        if (rows != 1) {
            this.traceHandler.traceError(TAG, "discardArrived - Error deleting message {" + id + "} from database: Rows affected = " + rows);
            return false;
        } else {
            int count = this.getArrivedRowCount(clientHandle);
            this.traceHandler.traceDebug(TAG, "discardArrived - Message deleted successfully. - messages in db for this clientHandle " + count);
            return true;
        }
    }

    public Iterator<MessageStore.StoredMessage> getAllArrivedMessages(final String clientHandle) {
        return new Iterator<MessageStore.StoredMessage>() {
            private Cursor c;
            private boolean hasNext;
            private String[] selectionArgs = new String[]{clientHandle};

            {
                DatabaseMessageStore.this.db = DatabaseMessageStore.this.mqttDb.getWritableDatabase();
                if (clientHandle == null) {
                    this.c = DatabaseMessageStore.this.db.query("MqttArrivedMessageTable", (String[])null, (String)null, (String[])null, (String)null, (String)null, "mtimestamp ASC");
                } else {
                    this.c = DatabaseMessageStore.this.db.query("MqttArrivedMessageTable", (String[])null, "clientHandle=?", this.selectionArgs, (String)null, (String)null, "mtimestamp ASC");
                }

                this.hasNext = this.c.moveToFirst();
            }

            public boolean hasNext() {
                if (!this.hasNext) {
                    this.c.close();
                }

                return this.hasNext;
            }

            public MessageStore.StoredMessage next() {
                String messageId = this.c.getString(this.c.getColumnIndex("messageId"));
                String clientHandlex = this.c.getString(this.c.getColumnIndex("clientHandle"));
                String topic = this.c.getString(this.c.getColumnIndex("destinationName"));
                byte[] payload = this.c.getBlob(this.c.getColumnIndex("payload"));
                int qos = this.c.getInt(this.c.getColumnIndex("qos"));
                boolean retained = Boolean.parseBoolean(this.c.getString(this.c.getColumnIndex("retained")));
                boolean dup = Boolean.parseBoolean(this.c.getString(this.c.getColumnIndex("duplicate")));
                DatabaseMessageStore.MqttMessageHack message = DatabaseMessageStore.this.new MqttMessageHack(payload);
                message.setQos(qos);
                message.setRetained(retained);
                message.setDuplicate(dup);
                this.hasNext = this.c.moveToNext();
                return DatabaseMessageStore.this.new DbStoredData(messageId, clientHandlex, topic, message);
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }

            protected void finalize() throws Throwable {
                this.c.close();
                super.finalize();
            }
        };
    }

    public void clearArrivedMessages(String clientHandle) {
        this.db = this.mqttDb.getWritableDatabase();
        String[] selectionArgs = new String[]{clientHandle};
        int rows = 0;
        if (clientHandle == null) {
            this.traceHandler.traceDebug(TAG, "clearArrivedMessages: clearing the table");
            rows = this.db.delete("MqttArrivedMessageTable", (String)null, (String[])null);
        } else {
            this.traceHandler.traceDebug(TAG, "clearArrivedMessages: clearing the table of " + clientHandle + " messages");
            rows = this.db.delete("MqttArrivedMessageTable", "clientHandle=?", selectionArgs);
        }

        this.traceHandler.traceDebug(TAG, "clearArrivedMessages: rows affected = " + rows);
    }

    public void close() {
        if (this.db != null) {
            this.db.close();
        }

    }

    private class MqttMessageHack extends MqttMessage {
        public MqttMessageHack(byte[] payload) {
            super(payload);
        }

        protected void setDuplicate(boolean dup) {
            super.setDuplicate(dup);
        }
    }

    private class DbStoredData implements MessageStore.StoredMessage {
        private String messageId;
        private String clientHandle;
        private String topic;
        private MqttMessage message;

        DbStoredData(String messageId, String clientHandle, String topic, MqttMessage message) {
            this.messageId = messageId;
            this.topic = topic;
            this.message = message;
        }

        public String getMessageId() {
            return this.messageId;
        }

        public String getClientHandle() {
            return this.clientHandle;
        }

        public String getTopic() {
            return this.topic;
        }

        public MqttMessage getMessage() {
            return this.message;
        }
    }

    private static class MQTTDatabaseHelper extends SQLiteOpenHelper {
        private static String TAG = "MQTTDatabaseHelper";
        private static final String DATABASE_NAME = "mqttAndroidService.db";
        private static final int DATABASE_VERSION = 1;
        private MqttTraceHandler traceHandler = null;

        public MQTTDatabaseHelper(MqttTraceHandler traceHandler, Context context) {
            super(context, "mqttAndroidService.db", (SQLiteDatabase.CursorFactory)null, 1);
            this.traceHandler = traceHandler;
        }

        public void onCreate(SQLiteDatabase database) {
            String createArrivedTableStatement = "CREATE TABLE MqttArrivedMessageTable(messageId TEXT PRIMARY KEY, clientHandle TEXT, destinationName TEXT, payload BLOB, qos INTEGER, retained TEXT, duplicate TEXT, mtimestamp INTEGER);";
            this.traceHandler.traceDebug(TAG, "onCreate {" + createArrivedTableStatement + "}");

            try {
                database.execSQL(createArrivedTableStatement);
                this.traceHandler.traceDebug(TAG, "created the table");
            } catch (SQLException var4) {
                this.traceHandler.traceException(TAG, "onCreate", var4);
                throw var4;
            }
        }

        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            this.traceHandler.traceDebug(TAG, "onUpgrade");

            try {
                db.execSQL("DROP TABLE IF EXISTS MqttArrivedMessageTable");
            } catch (SQLException var5) {
                this.traceHandler.traceException(TAG, "onUpgrade", var5);
                throw var5;
            }

            this.onCreate(db);
            this.traceHandler.traceDebug(TAG, "onUpgrade complete");
        }
    }

}

MessageStore.java


package com.iot.listeninsoul.service;

import java.util.Iterator;

import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * <p>
 * Mechanism for persisting messages until we know they have been received
 * </p>
 * <ul>
 * <li>A Service should store messages as they arrive via
 * {@link #storeArrived(String, String, MqttMessage)}.
 * <li>When a message has been passed to the consuming entity,
 * {@link #discardArrived(String, String)} should be called.
 * <li>To recover messages which have not been definitely passed to the
 * consumer, {@link MessageStore#getAllArrivedMessages(String)} is used.
 * <li>When a clean session is started {@link #clearArrivedMessages(String)} is
 * used.
 * </ul>
 */
interface MessageStore {

	String storeArrived(String var1, String var2, MqttMessage var3);

	boolean discardArrived(String var1, String var2);

	Iterator<StoredMessage> getAllArrivedMessages(String var1);

	void clearArrivedMessages(String var1);

	void close();

	public interface StoredMessage {
		String getMessageId();

		String getClientHandle();

		String getTopic();

		MqttMessage getMessage();
	}
}

MqttAndroidClient.java

package com.iot.listeninsoul.service;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.SparseArray;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttAsyncClient;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClientPersistence;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

/**
 * Enables an android application to communicate with an MQTT server using non-blocking methods.
 * <p>
 * Using the MQTT
 * android service to actually interface with MQTT server. It provides android applications a simple programming interface to all features of the MQTT version 3.1
 * specification including:
 * </p>
 * <ul>
 * <li>connect
 * <li>publish
 * <li>subscribe
 * <li>unsubscribe
 * <li>disconnect
 * </ul>
 */
public class MqttAndroidClient extends BroadcastReceiver implements IMqttAsyncClient {
    private static final String SERVICE_NAME = "MqttService";
    private static final int BIND_SERVICE_FLAG = 0;
    private static ExecutorService pool = Executors.newCachedThreadPool();
    private MyServiceConnection serviceConnection;
    private MqttService mqttService;
    private String clientHandle;
    Context myContext;
    private SparseArray<IMqttToken> tokenMap;
    private int tokenNumber;
    private String serverURI;
    private String clientId;
    private MqttClientPersistence persistence;
    private MqttConnectOptions connectOptions;
    private IMqttToken connectToken;
    private MqttCallback callback;
    private MqttTraceHandler traceCallback;
    private MqttAndroidClient.Ack messageAck;
    private boolean traceEnabled;
    private volatile boolean receiverRegistered;
    private volatile boolean bindedService;

    public MqttAndroidClient(Context context, String serverURI, String clientId) {
        this(context, serverURI, clientId, (MqttClientPersistence)null, MqttAndroidClient.Ack.AUTO_ACK);
    }

    public MqttAndroidClient(Context ctx, String serverURI, String clientId, MqttAndroidClient.Ack ackType) {
        this(ctx, serverURI, clientId, (MqttClientPersistence)null, ackType);
    }

    public MqttAndroidClient(Context ctx, String serverURI, String clientId, MqttClientPersistence persistence) {
        this(ctx, serverURI, clientId, persistence, MqttAndroidClient.Ack.AUTO_ACK);
    }

    public MqttAndroidClient(Context context, String serverURI, String clientId, MqttClientPersistence persistence, MqttAndroidClient.Ack ackType) {
        this.serviceConnection = new MyServiceConnection();
        this.tokenMap = new SparseArray();
        this.tokenNumber = 0;
        this.persistence = null;
        this.traceEnabled = false;
        this.receiverRegistered = false;
        this.bindedService = false;
        this.myContext = context;
        this.serverURI = serverURI;
        this.clientId = clientId;
        this.persistence = persistence;
        this.messageAck = ackType;
    }

    public boolean isConnected() {
        return this.clientHandle != null && this.mqttService != null ? this.mqttService.isConnected(this.clientHandle) : false;
    }

    public String getClientId() {
        return this.clientId;
    }

    public String getServerURI() {
        return this.serverURI;
    }

    public void close() {
        if (this.clientHandle == null) {
            System.out.println(this.serverURI);
            System.out.println(this.clientId);
            System.out.println(this.myContext.getApplicationInfo().packageName);
            System.out.println(this.persistence);
            this.clientHandle = this.mqttService.getClient(this.serverURI, this.clientId, this.myContext.getApplicationInfo().packageName, this.persistence);
        }

        this.mqttService.close(this.clientHandle);
    }

    public IMqttToken connect() throws MqttException {
        return this.connect((Object)null, (IMqttActionListener)null);
    }

    public IMqttToken connect(MqttConnectOptions options) throws MqttException {
        return this.connect(options, (Object)null, (IMqttActionListener)null);
    }

    public IMqttToken connect(Object userContext, IMqttActionListener callback) throws MqttException {
        return this.connect(new MqttConnectOptions(), userContext, callback);
    }

    public IMqttToken connect(MqttConnectOptions options, Object userContext, IMqttActionListener callback) throws MqttException {

        IMqttToken token = new MqttTokenAndroid(this, userContext, callback);
        this.connectOptions = options;
        this.connectToken = token;
        if (this.mqttService == null) {

            Intent serviceStartIntent = new Intent();
            serviceStartIntent.setClassName(this.myContext, String.valueOf(MqttService.class));

            Object service = this.myContext.startService(serviceStartIntent);
            if (service == null) {
                IMqttActionListener listener = token.getActionCallback();
                if (listener != null) {
                    listener.onFailure(token, new RuntimeException("cannot start service MqttService"));
                }
            }

            this.myContext.bindService(serviceStartIntent, this.serviceConnection, Context.BIND_AUTO_CREATE);
            if (!this.receiverRegistered) {
                this.registerReceiver(this);
            }

        } else {
            pool.execute(new Runnable() {
                public void run() {
                    MqttAndroidClient.this.doConnect();
                    if (!MqttAndroidClient.this.receiverRegistered) {
                        MqttAndroidClient.this.registerReceiver(MqttAndroidClient.this);
                    }

                }
            });
        }

        return token;
    }

    private void registerReceiver(BroadcastReceiver receiver) {
        IntentFilter filter = new IntentFilter();
        filter.addAction("MqttService.callbackToActivity.v0");
        LocalBroadcastManager.getInstance(this.myContext).registerReceiver(receiver, filter);
        this.receiverRegistered = true;
    }

    private void doConnect() {
        if (this.clientHandle == null) {
            this.clientHandle = this.mqttService.getClient(this.serverURI, this.clientId, this.myContext.getApplicationInfo().packageName, this.persistence);
        }

        this.mqttService.setTraceEnabled(this.traceEnabled);
        this.mqttService.setTraceCallbackId(this.clientHandle);
        String activityToken = this.storeToken(this.connectToken);

        try {
            this.mqttService.connect(this.clientHandle, this.connectOptions, (String)null, activityToken);
        } catch (MqttException var4) {
            IMqttActionListener listener = this.connectToken.getActionCallback();
            if (listener != null) {
                listener.onFailure(this.connectToken, var4);
            }
        }

    }

    public IMqttToken disconnect() throws MqttException {
        IMqttToken token = new MqttTokenAndroid(this, (Object)null, (IMqttActionListener)null);
        String activityToken = this.storeToken(token);
        this.mqttService.disconnect(this.clientHandle, (String)null, activityToken);
        return token;
    }

    public IMqttToken disconnect(long quiesceTimeout) throws MqttException {
        IMqttToken token = new MqttTokenAndroid(this, (Object)null, (IMqttActionListener)null);
        String activityToken = this.storeToken(token);
        this.mqttService.disconnect(this.clientHandle, quiesceTimeout, (String)null, activityToken);
        return token;
    }

    public IMqttToken disconnect(Object userContext, IMqttActionListener callback) throws MqttException {
        IMqttToken token = new MqttTokenAndroid(this, userContext, callback);
        String activityToken = this.storeToken(token);
        this.mqttService.disconnect(this.clientHandle, (String)null, activityToken);
        return token;
    }

    public IMqttToken disconnect(long quiesceTimeout, Object userContext, IMqttActionListener callback) throws MqttException {
        IMqttToken token = new MqttTokenAndroid(this, userContext, callback);
        String activityToken = this.storeToken(token);
        this.mqttService.disconnect(this.clientHandle, quiesceTimeout, (String)null, activityToken);
        return token;
    }

    public IMqttDeliveryToken publish(String topic, byte[] payload, int qos, boolean retained) throws MqttException, MqttPersistenceException {
        return this.publish(topic, payload, qos, retained, (Object)null, (IMqttActionListener)null);
    }

    public IMqttDeliveryToken publish(String topic, MqttMessage message) throws MqttException, MqttPersistenceException {
        return this.publish(topic, message, (Object)null, (IMqttActionListener)null);
    }

    public IMqttDeliveryToken publish(String topic, byte[] payload, int qos, boolean retained, Object userContext, IMqttActionListener callback) throws MqttException, MqttPersistenceException {
        MqttMessage message = new MqttMessage(payload);
        message.setQos(qos);
        message.setRetained(retained);
        MqttDeliveryTokenAndroid token = new MqttDeliveryTokenAndroid(this, userContext, callback, message);
        String activityToken = this.storeToken(token);
        IMqttDeliveryToken internalToken = this.mqttService.publish(this.clientHandle, topic, payload, qos, retained, (String)null, activityToken);
        token.setDelegate(internalToken);
        return token;
    }

    public IMqttDeliveryToken publish(String topic, MqttMessage message, Object userContext, IMqttActionListener callback) throws MqttException, MqttPersistenceException {
        MqttDeliveryTokenAndroid token = new MqttDeliveryTokenAndroid(this, userContext, callback, message);
        String activityToken = this.storeToken(token);
        IMqttDeliveryToken internalToken = this.mqttService.publish(this.clientHandle, topic, message, (String)null, activityToken);
        token.setDelegate(internalToken);
        return token;
    }

    public IMqttToken subscribe(String topic, int qos) throws MqttException, MqttSecurityException {
        return this.subscribe(topic, qos, (Object)null, (IMqttActionListener)null);
    }

    public IMqttToken subscribe(String[] topic, int[] qos) throws MqttException, MqttSecurityException {
        return this.subscribe(topic, qos, (Object)null, (IMqttActionListener)null);
    }

    public IMqttToken subscribe(String topic, int qos, Object userContext, IMqttActionListener callback) throws MqttException {
        IMqttToken token = new MqttTokenAndroid(this, userContext, callback, new String[]{topic});
        String activityToken = this.storeToken(token);
        this.mqttService.subscribe(this.clientHandle, topic, qos, (String)null, activityToken);
        return token;
    }

    public IMqttToken subscribe(String[] topic, int[] qos, Object userContext, IMqttActionListener callback) throws MqttException {
        IMqttToken token = new MqttTokenAndroid(this, userContext, callback, topic);
        String activityToken = this.storeToken(token);
        this.mqttService.subscribe(this.clientHandle, topic, qos, (String)null, activityToken);
        return token;
    }

    public IMqttToken subscribe(String topicFilter, int qos, Object userContext, IMqttActionListener callback, IMqttMessageListener messageListener) throws MqttException {
        return this.subscribe(new String[]{topicFilter}, new int[]{qos}, userContext, callback, new IMqttMessageListener[]{messageListener});
    }

    public IMqttToken subscribe(String topicFilter, int qos, IMqttMessageListener messageListener) throws MqttException {
        return this.subscribe(topicFilter, qos, (Object)null, (IMqttActionListener)null, messageListener);
    }

    public IMqttToken subscribe(String[] topicFilters, int[] qos, IMqttMessageListener[] messageListeners) throws MqttException {
        return this.subscribe(topicFilters, qos, (Object)null, (IMqttActionListener)null, messageListeners);
    }

    public IMqttToken subscribe(String[] topicFilters, int[] qos, Object userContext, IMqttActionListener callback, IMqttMessageListener[] messageListeners) throws MqttException {
        IMqttToken token = new MqttTokenAndroid(this, userContext, callback, topicFilters);
        String activityToken = this.storeToken(token);
        this.mqttService.subscribe(this.clientHandle, topicFilters, qos, (String)null, activityToken, messageListeners);
        return null;
    }

    public IMqttToken unsubscribe(String topic) throws MqttException {
        return this.unsubscribe((String)topic, (Object)null, (IMqttActionListener)null);
    }

    public IMqttToken unsubscribe(String[] topic) throws MqttException {
        return this.unsubscribe((String[])topic, (Object)null, (IMqttActionListener)null);
    }

    public IMqttToken unsubscribe(String topic, Object userContext, IMqttActionListener callback) throws MqttException {
        IMqttToken token = new MqttTokenAndroid(this, userContext, callback);
        String activityToken = this.storeToken(token);
        this.mqttService.unsubscribe(this.clientHandle, topic, (String)null, activityToken);
        return token;
    }

    public IMqttToken unsubscribe(String[] topic, Object userContext, IMqttActionListener callback) throws MqttException {
        IMqttToken token = new MqttTokenAndroid(this, userContext, callback);
        String activityToken = this.storeToken(token);
        this.mqttService.unsubscribe(this.clientHandle, topic, (String)null, activityToken);
        return token;
    }

    public IMqttDeliveryToken[] getPendingDeliveryTokens() {
        return this.mqttService.getPendingDeliveryTokens(this.clientHandle);
    }

    public void setCallback(MqttCallback callback) {
        this.callback = callback;
    }

    public void setTraceCallback(MqttTraceHandler traceCallback) {
        this.traceCallback = traceCallback;
    }

    public void setTraceEnabled(boolean traceEnabled) {
        this.traceEnabled = traceEnabled;
        if (this.mqttService != null) {
            this.mqttService.setTraceEnabled(traceEnabled);
        }

    }

    public void onReceive(Context context, Intent intent) {
        Bundle data = intent.getExtras();
        String handleFromIntent = data.getString("MqttService.clientHandle");
        if (handleFromIntent != null && handleFromIntent.equals(this.clientHandle)) {
            String action = data.getString("MqttService.callbackAction");
            if ("connect".equals(action)) {
                this.connectAction(data);
            } else if ("connectExtended".equals(action)) {
                this.connectExtendedAction(data);
            } else if ("messageArrived".equals(action)) {
                this.messageArrivedAction(data);
            } else if ("subscribe".equals(action)) {
                this.subscribeAction(data);
            } else if ("unsubscribe".equals(action)) {
                this.unSubscribeAction(data);
            } else if ("send".equals(action)) {
                this.sendAction(data);
            } else if ("messageDelivered".equals(action)) {
                this.messageDeliveredAction(data);
            } else if ("onConnectionLost".equals(action)) {
                this.connectionLostAction(data);
            } else if ("disconnect".equals(action)) {
                this.disconnected(data);
            } else if ("trace".equals(action)) {
                this.traceAction(data);
            } else {
                this.mqttService.traceError("MqttService", "Callback action doesn't exist.");
            }

        }
    }

    public boolean acknowledgeMessage(String messageId) {
        if (this.messageAck == MqttAndroidClient.Ack.MANUAL_ACK) {
            Status status = this.mqttService.acknowledgeMessageArrival(this.clientHandle, messageId);
            return status == Status.OK;
        } else {
            return false;
        }
    }

    public void messageArrivedComplete(int messageId, int qos) throws MqttException {
        throw new UnsupportedOperationException();
    }

    public void setManualAcks(boolean manualAcks) {
        throw new UnsupportedOperationException();
    }

    private void connectAction(Bundle data) {
        IMqttToken token = this.connectToken;
        this.removeMqttToken(data);
        this.simpleAction(token, data);
    }

    private void disconnected(Bundle data) {
        this.clientHandle = null;
        IMqttToken token = this.removeMqttToken(data);
        if (token != null) {
            ((MqttTokenAndroid)token).notifyComplete();
        }

        if (this.callback != null) {
            this.callback.connectionLost((Throwable)null);
        }

    }

    private void connectionLostAction(Bundle data) {
        if (this.callback != null) {
            Exception reason = (Exception)data.getSerializable("MqttService.exception");
            this.callback.connectionLost(reason);
        }

    }

    private void connectExtendedAction(Bundle data) {
        if (this.callback instanceof MqttCallbackExtended) {
            boolean reconnect = data.getBoolean("MqttService.reconnect", false);
            String serverURI = data.getString("MqttService.serverURI");
            ((MqttCallbackExtended)this.callback).connectComplete(reconnect, serverURI);
        }

    }

    private void simpleAction(IMqttToken token, Bundle data) {
        if (token != null) {
            Status status = (Status)data.getSerializable("MqttService.callbackStatus");
            if (status == Status.OK) {
                ((MqttTokenAndroid)token).notifyComplete();
            } else {
                Exception exceptionThrown = (Exception)data.getSerializable("MqttService.exception");
                ((MqttTokenAndroid)token).notifyFailure(exceptionThrown);
            }
        } else {
            this.mqttService.traceError("MqttService", "simpleAction : token is null");
        }

    }

    private void sendAction(Bundle data) {
        IMqttToken token = this.getMqttToken(data);
        this.simpleAction(token, data);
    }

    private void subscribeAction(Bundle data) {
        IMqttToken token = this.removeMqttToken(data);
        this.simpleAction(token, data);
    }

    private void unSubscribeAction(Bundle data) {
        IMqttToken token = this.removeMqttToken(data);
        this.simpleAction(token, data);
    }

    private void messageDeliveredAction(Bundle data) {
        IMqttToken token = this.removeMqttToken(data);
        if (token != null && this.callback != null) {
            Status status = (Status)data.getSerializable("MqttService.callbackStatus");
            if (status == Status.OK && token instanceof IMqttDeliveryToken) {
                this.callback.deliveryComplete((IMqttDeliveryToken)token);
            }
        }

    }

    private void messageArrivedAction(Bundle data) {
        if (this.callback != null) {
            String messageId = data.getString("MqttService.messageId");
            String destinationName = data.getString("MqttService.destinationName");
            ParcelableMqttMessage message = (ParcelableMqttMessage)data.getParcelable("MqttService.PARCEL");

            try {
                if (this.messageAck == MqttAndroidClient.Ack.AUTO_ACK) {
                    this.callback.messageArrived(destinationName, message);
                    this.mqttService.acknowledgeMessageArrival(this.clientHandle, messageId);
                } else {
                    message.messageId = messageId;
                    this.callback.messageArrived(destinationName, message);
                }
            } catch (Exception var6) {
            }
        }

    }

    private void traceAction(Bundle data) {
        if (this.traceCallback != null) {
            String severity = data.getString("MqttService.traceSeverity");
            String message = data.getString("MqttService.errorMessage");
            String tag = data.getString("MqttService.traceTag");
            if ("debug".equals(severity)) {
                this.traceCallback.traceDebug(tag, message);
            } else if ("error".equals(severity)) {
                this.traceCallback.traceError(tag, message);
            } else {
                Exception e = (Exception)data.getSerializable("MqttService.exception");
                this.traceCallback.traceException(tag, message, e);
            }
        }

    }

    private synchronized String storeToken(IMqttToken token) {
        this.tokenMap.put(this.tokenNumber, token);
        return Integer.toString(this.tokenNumber++);
    }

    private synchronized IMqttToken removeMqttToken(Bundle data) {
        String activityToken = data.getString("MqttService.activityToken");
        if (activityToken != null) {
            int tokenNumber = Integer.parseInt(activityToken);
            IMqttToken token = (IMqttToken)this.tokenMap.get(tokenNumber);
            this.tokenMap.delete(tokenNumber);
            return token;
        } else {
            return null;
        }
    }

    private synchronized IMqttToken getMqttToken(Bundle data) {
        String activityToken = data.getString("MqttService.activityToken");
        IMqttToken token = (IMqttToken)this.tokenMap.get(Integer.parseInt(activityToken));
        return token;
    }

    public void setBufferOpts(DisconnectedBufferOptions bufferOpts) {
        this.mqttService.setBufferOpts(this.clientHandle, bufferOpts);
    }

    public int getBufferedMessageCount() {
        return this.mqttService.getBufferedMessageCount(this.clientHandle);
    }

    public MqttMessage getBufferedMessage(int bufferIndex) {
        return this.mqttService.getBufferedMessage(this.clientHandle, bufferIndex);
    }

    public void deleteBufferedMessage(int bufferIndex) {
        this.mqttService.deleteBufferedMessage(this.clientHandle, bufferIndex);
    }

    public SSLSocketFactory getSSLSocketFactory(InputStream keyStore, String password) throws MqttSecurityException {
        try {
            SSLContext ctx = null;
            SSLSocketFactory sslSockFactory = null;
            KeyStore ts = KeyStore.getInstance("BKS");
            ts.load(keyStore, password.toCharArray());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
            tmf.init(ts);
            TrustManager[] tm = tmf.getTrustManagers();
            ctx = SSLContext.getInstance("TLSv1");
            ctx.init((KeyManager[])null, tm, (SecureRandom)null);
            sslSockFactory = ctx.getSocketFactory();
            return sslSockFactory;
        } catch (KeyStoreException var8) {
            throw new MqttSecurityException(var8);
        } catch (CertificateException var9) {
            throw new MqttSecurityException(var9);
        } catch (FileNotFoundException var10) {
            throw new MqttSecurityException(var10);
        } catch (IOException var11) {
            throw new MqttSecurityException(var11);
        } catch (NoSuchAlgorithmException var12) {
            throw new MqttSecurityException(var12);
        } catch (KeyManagementException var13) {
            throw new MqttSecurityException(var13);
        }
    }

    public void disconnectForcibly() throws MqttException {
        throw new UnsupportedOperationException();
    }

    public void disconnectForcibly(long disconnectTimeout) throws MqttException {
        throw new UnsupportedOperationException();
    }

    public void disconnectForcibly(long quiesceTimeout, long disconnectTimeout) throws MqttException {
        throw new UnsupportedOperationException();
    }

    public void unregisterResources() {
        if (this.myContext != null && this.receiverRegistered) {
            synchronized(this) {
                LocalBroadcastManager.getInstance(this.myContext).unregisterReceiver(this);
                this.receiverRegistered = false;
            }

            if (this.bindedService) {
                try {
                    this.myContext.unbindService(this.serviceConnection);
                    this.bindedService = false;
                } catch (IllegalArgumentException var3) {
                }
            }
        }

    }

    public void registerResources(Context context) {
        if (context != null) {
            this.myContext = context;
            if (!this.receiverRegistered) {
                this.registerReceiver(this);
            }
        }

    }

    private final class MyServiceConnection implements ServiceConnection {
        private MyServiceConnection() {
        }

        public void onServiceConnected(ComponentName name, IBinder binder) {
            MqttAndroidClient.this.mqttService = ((MqttServiceBinder)binder).getService();
            MqttAndroidClient.this.bindedService = true;
            MqttAndroidClient.this.doConnect();
        }

        public void onServiceDisconnected(ComponentName name) {
            MqttAndroidClient.this.mqttService = null;
        }
    }

    public static enum Ack {
        AUTO_ACK,
        MANUAL_ACK;

        private Ack() {
        }
    }
}

MqttConnection.java

package com.iot.listeninsoul.service;

import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;


import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClientPersistence;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

class MqttConnection implements MqttCallbackExtended {
   private static final String TAG = "MqttConnection";
   private static final String NOT_CONNECTED = "not connected";
   private String serverURI;
   private String clientId;
   private MqttClientPersistence persistence = null;
   private MqttConnectOptions connectOptions;
   private String clientHandle;
   private String reconnectActivityToken = null;
   private MqttAsyncClient myClient = null;
   private MqttService service = null;
   private volatile boolean disconnected = true;
   private boolean cleanSession = true;
   private volatile boolean isConnecting = false;
   private Map<IMqttDeliveryToken, String> savedTopics = new HashMap();
   private Map<IMqttDeliveryToken, MqttMessage> savedSentMessages = new HashMap();
   private Map<IMqttDeliveryToken, String> savedActivityTokens = new HashMap();
   private Map<IMqttDeliveryToken, String> savedInvocationContexts = new HashMap();
   private PowerManager.WakeLock wakelock = null;
   private String wakeLockTag = null;
   private DisconnectedBufferOptions bufferOpts = null;

   public String getServerURI() {
      return this.serverURI;
   }

   public void setServerURI(String serverURI) {
      this.serverURI = serverURI;
   }

   public String getClientId() {
      return this.clientId;
   }

   public void setClientId(String clientId) {
      this.clientId = clientId;
   }

   public MqttConnectOptions getConnectOptions() {
      return this.connectOptions;
   }

   public void setConnectOptions(MqttConnectOptions connectOptions) {
      this.connectOptions = connectOptions;
   }

   public String getClientHandle() {
      return this.clientHandle;
   }

   public void setClientHandle(String clientHandle) {
      this.clientHandle = clientHandle;
   }

   MqttConnection(MqttService service, String serverURI, String clientId, MqttClientPersistence persistence, String clientHandle) {
      this.serverURI = serverURI.toString();
      this.service = service;
      this.clientId = clientId;
      this.persistence = persistence;
      this.clientHandle = clientHandle;
      StringBuffer buff = new StringBuffer(this.getClass().getCanonicalName());
      buff.append(" ");
      buff.append(clientId);
      buff.append(" ");
      buff.append("on host ");
      buff.append(serverURI);
      this.wakeLockTag = buff.toString();
   }

   public void connect(MqttConnectOptions options, String invocationContext, String activityToken) {
      this.connectOptions = options;
      this.reconnectActivityToken = activityToken;
      if (options != null) {
         this.cleanSession = options.isCleanSession();
      }

      if (this.connectOptions.isCleanSession()) {
         this.service.messageStore.clearArrivedMessages(this.clientHandle);
      }

      this.service.traceDebug("MqttConnection", "Connecting {" + this.serverURI + "} as {" + this.clientId + "}");
      final Bundle resultBundle = new Bundle();
      resultBundle.putString("MqttService.activityToken", activityToken);
      resultBundle.putString("MqttService.invocationContext", invocationContext);
      resultBundle.putString("MqttService.callbackAction", "connect");

      try {
         if (this.persistence == null) {
            File myDir = this.service.getExternalFilesDir("MqttConnection");
            if (myDir == null) {
               myDir = this.service.getDir("MqttConnection", 0);
               if (myDir == null) {
                  resultBundle.putString("MqttService.errorMessage", "Error! No external and internal storage available");
                  resultBundle.putSerializable("MqttService.exception", new MqttPersistenceException());
                  this.service.callbackToActivity(this.clientHandle, Status.ERROR, resultBundle);
                  return;
               }
            }

            this.persistence = new MqttDefaultFilePersistence(myDir.getAbsolutePath());
         }

         IMqttActionListener listener = new MqttConnection.MqttConnectionListener(resultBundle) {
            public void onSuccess(IMqttToken asyncActionToken) {
               MqttConnection.this.doAfterConnectSuccess(resultBundle);
               MqttConnection.this.service.traceDebug("MqttConnection", "connect success!");
            }

            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
               resultBundle.putString("MqttService.errorMessage", exception.getLocalizedMessage());
               resultBundle.putSerializable("MqttService.exception", exception);
               MqttConnection.this.service.traceError("MqttConnection", "connect fail, call connect to reconnect.reason:" + exception.getMessage());
               MqttConnection.this.doAfterConnectFail(resultBundle);
            }
         };
         if (this.myClient != null) {
            if (this.isConnecting) {
               this.service.traceDebug("MqttConnection", "myClient != null and the client is connecting. Connect return directly.");
               this.service.traceDebug("MqttConnection", "Connect return:isConnecting:" + this.isConnecting + ".disconnected:" + this.disconnected);
               return;
            }

            if (!this.disconnected) {
               this.service.traceDebug("MqttConnection", "myClient != null and the client is connected and notify!");
               this.doAfterConnectSuccess(resultBundle);
            } else {
               this.service.traceDebug("MqttConnection", "myClient != null and the client is not connected");
               this.service.traceDebug("MqttConnection", "Do Real connect!");
               this.setConnectingState(true);
               this.myClient.connect(this.connectOptions, invocationContext, listener);
            }
         } else {
            this.myClient = new MqttAsyncClient(this.serverURI, this.clientId, this.persistence, new AlarmPingSender(this.service));
            this.myClient.setCallback(this);
            this.service.traceDebug("MqttConnection", "Do Real connect!");
            this.setConnectingState(true);
            this.myClient.connect(this.connectOptions, invocationContext, listener);
         }
      } catch (Exception var6) {
         this.handleException(resultBundle, var6);
      }

   }

   private void doAfterConnectSuccess(Bundle resultBundle) {
      this.acquireWakeLock();
      this.service.callbackToActivity(this.clientHandle, Status.OK, resultBundle);
      this.deliverBacklog();
      this.setConnectingState(false);
      this.disconnected = false;
      this.releaseWakeLock();
   }

   public void connectComplete(boolean reconnect, String serverURI) {
      Bundle resultBundle = new Bundle();
      resultBundle.putString("MqttService.callbackAction", "connectExtended");
      resultBundle.putBoolean("MqttService.reconnect", reconnect);
      resultBundle.putString("MqttService.serverURI", serverURI);
      this.service.callbackToActivity(this.clientHandle, Status.OK, resultBundle);
   }

   private void doAfterConnectFail(Bundle resultBundle) {
      this.acquireWakeLock();
      this.disconnected = true;
      this.setConnectingState(false);
      this.service.callbackToActivity(this.clientHandle, Status.ERROR, resultBundle);
      this.releaseWakeLock();
   }

   private void handleException(Bundle resultBundle, Exception e) {
      resultBundle.putString("MqttService.errorMessage", e.getLocalizedMessage());
      resultBundle.putSerializable("MqttService.exception", e);
      this.service.callbackToActivity(this.clientHandle, Status.ERROR, resultBundle);
   }

   private void deliverBacklog() {
      Iterator backlog = this.service.messageStore.getAllArrivedMessages(this.clientHandle);

      while(backlog.hasNext()) {
         MessageStore.StoredMessage msgArrived = (MessageStore.StoredMessage)backlog.next();
         Bundle resultBundle = this.messageToBundle(msgArrived.getMessageId(), msgArrived.getTopic(), msgArrived.getMessage());
         resultBundle.putString("MqttService.callbackAction", "messageArrived");
         this.service.callbackToActivity(this.clientHandle, Status.OK, resultBundle);
      }

   }

   private Bundle messageToBundle(String messageId, String topic, MqttMessage message) {
      Bundle result = new Bundle();
      result.putString("MqttService.messageId", messageId);
      result.putString("MqttService.destinationName", topic);
      result.putParcelable("MqttService.PARCEL", new ParcelableMqttMessage(message));
      return result;
   }

   void close() {
      this.service.traceDebug("MqttConnection", "close()");

      try {
         if (this.myClient != null) {
            this.myClient.close();
         }
      } catch (MqttException var2) {
         this.handleException(new Bundle(), var2);
      }

   }

   void disconnect(long quiesceTimeout, String invocationContext, String activityToken) {
      this.service.traceDebug("MqttConnection", "disconnect()");
      this.disconnected = true;
      Bundle resultBundle = new Bundle();
      resultBundle.putString("MqttService.activityToken", activityToken);
      resultBundle.putString("MqttService.invocationContext", invocationContext);
      resultBundle.putString("MqttService.callbackAction", "disconnect");
      if (this.myClient != null && this.myClient.isConnected()) {
         MqttConnectionListener listener = new MqttConnection.MqttConnectionListener(resultBundle);

         try {
            this.myClient.disconnect(quiesceTimeout, invocationContext, listener);
         } catch (Exception var8) {
            this.handleException(resultBundle, var8);
         }
      } else {
         resultBundle.putString("MqttService.errorMessage", "not connected");
         this.service.traceError("disconnect", "not connected");
         this.service.callbackToActivity(this.clientHandle, Status.ERROR, resultBundle);
      }

      if (this.connectOptions != null && this.connectOptions.isCleanSession()) {
         this.service.messageStore.clearArrivedMessages(this.clientHandle);
      }

      this.releaseWakeLock();
   }

   void disconnect(String invocationContext, String activityToken) {
      this.service.traceDebug("MqttConnection", "disconnect()");
      this.disconnected = true;
      Bundle resultBundle = new Bundle();
      resultBundle.putString("MqttService.activityToken", activityToken);
      resultBundle.putString("MqttService.invocationContext", invocationContext);
      resultBundle.putString("MqttService.callbackAction", "disconnect");
      if (this.myClient != null && this.myClient.isConnected()) {
         MqttConnection.MqttConnectionListener listener = new MqttConnection.MqttConnectionListener(resultBundle);

         try {
            this.myClient.disconnect(invocationContext, listener);
         } catch (Exception var6) {
            this.handleException(resultBundle, var6);
         }
      } else {
         resultBundle.putString("MqttService.errorMessage", "not connected");
         this.service.traceError("disconnect", "not connected");
         this.service.callbackToActivity(this.clientHandle, Status.ERROR, resultBundle);
      }

      if (this.connectOptions != null && this.connectOptions.isCleanSession()) {
         this.service.messageStore.clearArrivedMessages(this.clientHandle);
      }

      this.releaseWakeLock();
   }

   public boolean isConnected() {
      return this.myClient != null ? this.myClient.isConnected() : false;
   }

   public IMqttDeliveryToken publish(String topic, byte[] payload, int qos, boolean retained, String invocationContext, String activityToken) {
      Bundle resultBundle = new Bundle();
      resultBundle.putString("MqttService.callbackAction", "send");
      resultBundle.putString("MqttService.activityToken", activityToken);
      resultBundle.putString("MqttService.invocationContext", invocationContext);
      IMqttDeliveryToken sendToken = null;
      if (this.myClient != null && this.myClient.isConnected()) {
         MqttConnectionListener listener = new MqttConnection.MqttConnectionListener(resultBundle);

         try {
            MqttMessage message = new MqttMessage(payload);
            message.setQos(qos);
            message.setRetained(retained);
            sendToken = this.myClient.publish(topic, payload, qos, retained, invocationContext, listener);
            this.storeSendDetails(topic, message, sendToken, invocationContext, activityToken);
         } catch (Exception var11) {
            this.handleException(resultBundle, var11);
         }
      } else {
         resultBundle.putString("MqttService.errorMessage", "not connected");
         this.service.traceError("send", "not connected");
         this.service.callbackToActivity(this.clientHandle, Status.ERROR, resultBundle);
      }

      return sendToken;
   }

   public IMqttDeliveryToken publish(String topic, MqttMessage message, String invocationContext, String activityToken) {
      Bundle resultBundle = new Bundle();
      resultBundle.putString("MqttService.callbackAction", "send");
      resultBundle.putString("MqttService.activityToken", activityToken);
      resultBundle.putString("MqttService.invocationContext", invocationContext);
      IMqttDeliveryToken sendToken = null;
      MqttConnection.MqttConnectionListener listener;
      if (this.myClient != null && this.myClient.isConnected()) {
         listener = new MqttConnection.MqttConnectionListener(resultBundle);

         try {
            sendToken = this.myClient.publish(topic, message, invocationContext, listener);
            this.storeSendDetails(topic, message, sendToken, invocationContext, activityToken);
         } catch (Exception var10) {
            this.handleException(resultBundle, var10);
         }
      } else if (this.myClient != null && this.bufferOpts != null && this.bufferOpts.isBufferEnabled()) {
         listener = new MqttConnection.MqttConnectionListener(resultBundle);

         try {
            sendToken = this.myClient.publish(topic, message, invocationContext, listener);
            this.storeSendDetails(topic, message, sendToken, invocationContext, activityToken);
         } catch (Exception var9) {
            this.handleException(resultBundle, var9);
         }
      } else {
         Log.i("MqttConnection", "Client is not connected, so not sending message");
         resultBundle.putString("MqttService.errorMessage", "not connected");
         this.service.traceError("send", "not connected");
         this.service.callbackToActivity(this.clientHandle, Status.ERROR, resultBundle);
      }

      return sendToken;
   }

   public void subscribe(String topic, int qos, String invocationContext, String activityToken) {
      this.service.traceDebug("MqttConnection", "subscribe({" + topic + "}," + qos + ",{" + invocationContext + "}, {" + activityToken + "}");
      Bundle resultBundle = new Bundle();
      resultBundle.putString("MqttService.callbackAction", "subscribe");
      resultBundle.putString("MqttService.activityToken", activityToken);
      resultBundle.putString("MqttService.invocationContext", invocationContext);
      if (this.myClient != null && this.myClient.isConnected()) {
         MqttConnection.MqttConnectionListener listener = new MqttConnection.MqttConnectionListener(resultBundle);

         try {
            this.myClient.subscribe(topic, qos, invocationContext, listener);
         } catch (Exception var8) {
            this.handleException(resultBundle, var8);
         }
      } else {
         resultBundle.putString("MqttService.errorMessage", "not connected");
         this.service.traceError("subscribe", "not connected");
         this.service.callbackToActivity(this.clientHandle, Status.ERROR, resultBundle);
      }

   }

   public void subscribe(String[] topic, int[] qos, String invocationContext, String activityToken) {
      this.service.traceDebug("MqttConnection", "subscribe({" + topic + "}," + qos + ",{" + invocationContext + "}, {" + activityToken + "}");
      Bundle resultBundle = new Bundle();
      resultBundle.putString("MqttService.callbackAction", "subscribe");
      resultBundle.putString("MqttService.activityToken", activityToken);
      resultBundle.putString("MqttService.invocationContext", invocationContext);
      if (this.myClient != null && this.myClient.isConnected()) {
         MqttConnectionListener listener = new MqttConnection.MqttConnectionListener(resultBundle);

         try {
            this.myClient.subscribe(topic, qos, invocationContext, listener);
         } catch (Exception var8) {
            this.handleException(resultBundle, var8);
         }
      } else {
         resultBundle.putString("MqttService.errorMessage", "not connected");
         this.service.traceError("subscribe", "not connected");
         this.service.callbackToActivity(this.clientHandle, Status.ERROR, resultBundle);
      }

   }

   public void subscribe(String[] topicFilters, int[] qos, String invocationContext, String activityToken, IMqttMessageListener[] messageListeners) {
      this.service.traceDebug("MqttConnection", "subscribe({" + topicFilters + "}," + qos + ",{" + invocationContext + "}, {" + activityToken + "}");
      Bundle resultBundle = new Bundle();
      resultBundle.putString("MqttService.callbackAction", "subscribe");
      resultBundle.putString("MqttService.activityToken", activityToken);
      resultBundle.putString("MqttService.invocationContext", invocationContext);
      if (this.myClient != null && this.myClient.isConnected()) {
         new MqttConnection.MqttConnectionListener(resultBundle);

         try {
            this.myClient.subscribe(topicFilters, qos, messageListeners);
         } catch (Exception var9) {
            this.handleException(resultBundle, var9);
         }
      } else {
         resultBundle.putString("MqttService.errorMessage", "not connected");
         this.service.traceError("subscribe", "not connected");
         this.service.callbackToActivity(this.clientHandle, Status.ERROR, resultBundle);
      }

   }

   void unsubscribe(String topic, String invocationContext, String activityToken) {
      this.service.traceDebug("MqttConnection", "unsubscribe({" + topic + "},{" + invocationContext + "}, {" + activityToken + "})");
      Bundle resultBundle = new Bundle();
      resultBundle.putString("MqttService.callbackAction", "unsubscribe");
      resultBundle.putString("MqttService.activityToken", activityToken);
      resultBundle.putString("MqttService.invocationContext", invocationContext);
      if (this.myClient != null && this.myClient.isConnected()) {
         MqttConnectionListener listener = new MqttConnection.MqttConnectionListener(resultBundle);

         try {
            this.myClient.unsubscribe(topic, invocationContext, listener);
         } catch (Exception var7) {
            this.handleException(resultBundle, var7);
         }
      } else {
         resultBundle.putString("MqttService.errorMessage", "not connected");
         this.service.traceError("subscribe", "not connected");
         this.service.callbackToActivity(this.clientHandle, Status.ERROR, resultBundle);
      }

   }

   void unsubscribe(String[] topic, String invocationContext, String activityToken) {
      this.service.traceDebug("MqttConnection", "unsubscribe({" + topic + "},{" + invocationContext + "}, {" + activityToken + "})");
      Bundle resultBundle = new Bundle();
      resultBundle.putString("MqttService.callbackAction", "unsubscribe");
      resultBundle.putString("MqttService.activityToken", activityToken);
      resultBundle.putString("MqttService.invocationContext", invocationContext);
      if (this.myClient != null && this.myClient.isConnected()) {
         MqttConnection.MqttConnectionListener listener = new MqttConnection.MqttConnectionListener(resultBundle);

         try {
            this.myClient.unsubscribe(topic, invocationContext, listener);
         } catch (Exception var7) {
            this.handleException(resultBundle, var7);
         }
      } else {
         resultBundle.putString("MqttService.errorMessage", "not connected");
         this.service.traceError("subscribe", "not connected");
         this.service.callbackToActivity(this.clientHandle, Status.ERROR, resultBundle);
      }

   }

   public IMqttDeliveryToken[] getPendingDeliveryTokens() {
      return this.myClient.getPendingDeliveryTokens();
   }

   public void connectionLost(Throwable why) {
      this.service.traceDebug("MqttConnection", "connectionLost(" + why.getMessage() + ")");
      this.disconnected = true;

      try {
         this.myClient.disconnect((Object)null, new IMqttActionListener() {
            public void onSuccess(IMqttToken asyncActionToken) {
            }

            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            }
         });
      } catch (Exception var3) {
      }

      Bundle resultBundle = new Bundle();
      resultBundle.putString("MqttService.callbackAction", "onConnectionLost");
      if (why != null) {
         resultBundle.putString("MqttService.errorMessage", why.getMessage());
         if (why instanceof MqttException) {
            resultBundle.putSerializable("MqttService.exception", why);
         }

         resultBundle.putString("MqttService.exceptionStack", Log.getStackTraceString(why));
      }

      this.service.callbackToActivity(this.clientHandle, Status.OK, resultBundle);
      this.releaseWakeLock();
   }

   public void deliveryComplete(IMqttDeliveryToken messageToken) {
      this.service.traceDebug("MqttConnection", "deliveryComplete(" + messageToken + ")");
      MqttMessage message = (MqttMessage)this.savedSentMessages.remove(messageToken);
      if (message != null) {
         String topic = (String)this.savedTopics.remove(messageToken);
         String activityToken = (String)this.savedActivityTokens.remove(messageToken);
         String invocationContext = (String)this.savedInvocationContexts.remove(messageToken);
         Bundle resultBundle = this.messageToBundle((String)null, topic, message);
         if (activityToken != null) {
            resultBundle.putString("MqttService.callbackAction", "send");
            resultBundle.putString("MqttService.activityToken", activityToken);
            resultBundle.putString("MqttService.invocationContext", invocationContext);
            this.service.callbackToActivity(this.clientHandle, Status.OK, resultBundle);
         }

         resultBundle.putString("MqttService.callbackAction", "messageDelivered");
         this.service.callbackToActivity(this.clientHandle, Status.OK, resultBundle);
      }

   }

   public void messageArrived(String topic, MqttMessage message) throws Exception {
      this.service.traceDebug("MqttConnection", "messageArrived(" + topic + ",{" + message.toString() + "})");
      String messageId = this.service.messageStore.storeArrived(this.clientHandle, topic, message);
      Bundle resultBundle = this.messageToBundle(messageId, topic, message);
      resultBundle.putString("MqttService.callbackAction", "messageArrived");
      resultBundle.putString("MqttService.messageId", messageId);
      this.service.callbackToActivity(this.clientHandle, Status.OK, resultBundle);
   }

   private void storeSendDetails(String topic, MqttMessage msg, IMqttDeliveryToken messageToken, String invocationContext, String activityToken) {
      this.savedTopics.put(messageToken, topic);
      this.savedSentMessages.put(messageToken, msg);
      this.savedActivityTokens.put(messageToken, activityToken);
      this.savedInvocationContexts.put(messageToken, invocationContext);
   }

   private void acquireWakeLock() {
      if (this.wakelock == null) {
         PowerManager pm = (PowerManager)this.service.getSystemService(Context.POWER_SERVICE);
         this.wakelock = pm.newWakeLock(1, this.wakeLockTag);
      }

      this.wakelock.acquire();
   }

   private void releaseWakeLock() {
      if (this.wakelock != null && this.wakelock.isHeld()) {
         this.wakelock.release();
      }

   }

   void offline() {
      if (!this.disconnected && !this.cleanSession) {
         Exception e = new Exception("Android offline");
         this.connectionLost(e);
      }

   }

   synchronized void reconnect() {
      if (this.isConnecting) {
         this.service.traceDebug("MqttConnection", "The client is connecting. Reconnect return directly.");
      } else if (!this.service.isOnline()) {
         this.service.traceDebug("MqttConnection", "The network is not reachable. Will not do reconnect");
      } else {
         if (this.disconnected && !this.cleanSession) {
            this.service.traceDebug("MqttConnection", "Do Real Reconnect!");
            final Bundle resultBundle = new Bundle();
            resultBundle.putString("MqttService.activityToken", this.reconnectActivityToken);
            resultBundle.putString("MqttService.invocationContext", (String)null);
            resultBundle.putString("MqttService.callbackAction", "connect");

            try {
               IMqttActionListener listener = new MqttConnection.MqttConnectionListener(resultBundle) {
                  public void onSuccess(IMqttToken asyncActionToken) {
                     MqttConnection.this.service.traceDebug("MqttConnection", "Reconnect Success!");
                     MqttConnection.this.service.traceDebug("MqttConnection", "DeliverBacklog when reconnect.");
                     MqttConnection.this.doAfterConnectSuccess(resultBundle);
                  }

                  public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                     resultBundle.putString("MqttService.errorMessage", exception.getLocalizedMessage());
                     resultBundle.putSerializable("MqttService.exception", exception);
                     MqttConnection.this.service.callbackToActivity(MqttConnection.this.clientHandle, Status.ERROR, resultBundle);
                     MqttConnection.this.doAfterConnectFail(resultBundle);
                  }
               };
               this.myClient.connect(this.connectOptions, (Object)null, listener);
               this.setConnectingState(true);
            } catch (MqttException var3) {
               this.service.traceError("MqttConnection", "Cannot reconnect to remote server." + var3.getMessage());
               this.setConnectingState(false);
               this.handleException(resultBundle, var3);
            }
         }

      }
   }

   synchronized void setConnectingState(boolean isConnecting) {
      this.isConnecting = isConnecting;
   }

   public void setBufferOpts(DisconnectedBufferOptions bufferOpts) {
      this.bufferOpts = bufferOpts;
      this.myClient.setBufferOpts(bufferOpts);
   }

   public int getBufferedMessageCount() {
      return this.myClient.getBufferedMessageCount();
   }

   public MqttMessage getBufferedMessage(int bufferIndex) {
      return this.myClient.getBufferedMessage(bufferIndex);
   }

   public void deleteBufferedMessage(int bufferIndex) {
      this.myClient.deleteBufferedMessage(bufferIndex);
   }

   private class MqttConnectionListener implements IMqttActionListener {
      private final Bundle resultBundle;

      private MqttConnectionListener(Bundle resultBundle) {
         this.resultBundle = resultBundle;
      }

      public void onSuccess(IMqttToken asyncActionToken) {
         MqttConnection.this.service.callbackToActivity(MqttConnection.this.clientHandle, Status.OK, this.resultBundle);
      }

      public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
         this.resultBundle.putString("MqttService.errorMessage", exception.getLocalizedMessage());
         this.resultBundle.putSerializable("MqttService.exception", exception);
         MqttConnection.this.service.callbackToActivity(MqttConnection.this.clientHandle, Status.ERROR, this.resultBundle);
      }
   }
}

MqttDeliveryTokenAndroid.java

package com.iot.listeninsoul.service;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

// edit
class MqttDeliveryTokenAndroid extends MqttTokenAndroid implements IMqttDeliveryToken {
   private MqttMessage message;

   MqttDeliveryTokenAndroid(MqttAndroidClient client, Object userContext, IMqttActionListener listener, MqttMessage message) {
      super(client, userContext, listener);
      this.message = message;
   }

   public MqttMessage getMessage() throws MqttException {
      return this.message;
   }

   void setMessage(MqttMessage message) {
      this.message = message;
   }

   void notifyDelivery(MqttMessage delivered) {
      this.message = delivered;
      super.notifyComplete();
   }
}

MqttService.java

package com.iot.listeninsoul.service;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttClientPersistence;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;

/**
 * <p>
 * The android service which interfaces with an MQTT client implementation
 * </p>
 * <p>
 * The main API of MqttService is intended to pretty much mirror the
 * IMqttAsyncClient with appropriate adjustments for the Android environment.<br>
 * These adjustments usually consist of adding two parameters to each method :-
 * </p>
 * <ul>
 * <li>invocationContext - a string passed from the application to identify the
 * context of the operation (mainly included for support of the javascript API
 * implementation)</li>
 * <li>activityToken - a string passed from the Activity to relate back to a
 * callback method or other context-specific data</li>
 * </ul>
 * <p>
 * To support multiple client connections, the bulk of the MQTT work is
 * delegated to MqttConnection objects. These are identified by "client
 * handle" strings, which is how the Activity, and the higher-level APIs refer
 * to them.
 * </p>
 * <p>
 * Activities using this service are expected to start it and bind to it using
 * the BIND_AUTO_CREATE flag. The life cycle of this service is based on this
 * approach.
 * </p>
 */

// edit
@SuppressLint("Registered")
public class MqttService extends Service implements MqttTraceHandler {

    static final String TAG = "MqttService";
    private String traceCallbackId;
    private boolean traceEnabled = false;
    MessageStore messageStore;
    private MqttService.NetworkConnectionIntentReceiver networkConnectionMonitor;
    private MqttService.BackgroundDataPreferenceReceiver backgroundDataPreferenceMonitor;
    private volatile boolean backgroundDataEnabled = true;
    private MqttServiceBinder mqttServiceBinder;
    private Map<String, MqttConnection> connections = new ConcurrentHashMap();

    public MqttService() {
    }

    void callbackToActivity(String clientHandle, Status status, Bundle dataBundle) {
        Intent callbackIntent = new Intent("MqttService.callbackToActivity.v0");
        if (clientHandle != null) {
            callbackIntent.putExtra("MqttService.clientHandle", clientHandle);
        }

        callbackIntent.putExtra("MqttService.callbackStatus", status);
        if (dataBundle != null) {
            callbackIntent.putExtras(dataBundle);
        }

        LocalBroadcastManager.getInstance(this).sendBroadcast(callbackIntent);
    }

    public String getClient(String serverURI, String clientId, String contextId, MqttClientPersistence persistence) {
        String clientHandle = serverURI + ":" + clientId + ":" + contextId;
        if (!this.connections.containsKey(clientHandle)) {
            MqttConnection client = new MqttConnection(this, serverURI, clientId, persistence, clientHandle);
            this.connections.put(clientHandle, client);
        }

        return clientHandle;
    }

    public void connect(String clientHandle, MqttConnectOptions connectOptions, String invocationContext, String activityToken) throws MqttSecurityException, MqttException {
        MqttConnection client = this.getConnection(clientHandle);
        client.connect(connectOptions, invocationContext, activityToken);
    }

    void reconnect() {
        this.traceDebug("MqttService", "Reconnect to server, client size=" + this.connections.size());
        Iterator i$ = this.connections.values().iterator();

        while(i$.hasNext()) {
            MqttConnection client = (MqttConnection)i$.next();
            this.traceDebug("Reconnect Client:", client.getClientId() + '/' + client.getServerURI());
            if (this.isOnline()) {
                client.reconnect();
            }
        }

    }

    public void close(String clientHandle) {
        MqttConnection client = this.getConnection(clientHandle);
        client.close();
    }

    public void disconnect(String clientHandle, String invocationContext, String activityToken) {
        MqttConnection client = this.getConnection(clientHandle);
        client.disconnect(invocationContext, activityToken);
        this.connections.remove(clientHandle);
        this.stopSelf();
    }

    public void disconnect(String clientHandle, long quiesceTimeout, String invocationContext, String activityToken) {
        MqttConnection client = this.getConnection(clientHandle);
        client.disconnect(quiesceTimeout, invocationContext, activityToken);
        this.connections.remove(clientHandle);
        this.stopSelf();
    }

    public boolean isConnected(String clientHandle) {
        MqttConnection client = this.getConnection(clientHandle);
        return client.isConnected();
    }

    public IMqttDeliveryToken publish(String clientHandle, String topic, byte[] payload, int qos, boolean retained, String invocationContext, String activityToken) throws MqttPersistenceException, MqttException {
        MqttConnection client = this.getConnection(clientHandle);
        return client.publish(topic, payload, qos, retained, invocationContext, activityToken);
    }

    public IMqttDeliveryToken publish(String clientHandle, String topic, MqttMessage message, String invocationContext, String activityToken) throws MqttPersistenceException, MqttException {
        MqttConnection client = this.getConnection(clientHandle);
        return client.publish(topic, message, invocationContext, activityToken);
    }

    public void subscribe(String clientHandle, String topic, int qos, String invocationContext, String activityToken) {
        MqttConnection client = this.getConnection(clientHandle);
        client.subscribe(topic, qos, invocationContext, activityToken);
    }

    public void subscribe(String clientHandle, String[] topic, int[] qos, String invocationContext, String activityToken) {
        MqttConnection client = this.getConnection(clientHandle);
        client.subscribe(topic, qos, invocationContext, activityToken);
    }

    public void subscribe(String clientHandle, String[] topicFilters, int[] qos, String invocationContext, String activityToken, IMqttMessageListener[] messageListeners) {
        MqttConnection client = this.getConnection(clientHandle);
        client.subscribe(topicFilters, qos, invocationContext, activityToken, messageListeners);
    }

    public void unsubscribe(String clientHandle, String topic, String invocationContext, String activityToken) {
        MqttConnection client = this.getConnection(clientHandle);
        client.unsubscribe(topic, invocationContext, activityToken);
    }

    public void unsubscribe(String clientHandle, String[] topic, String invocationContext, String activityToken) {
        MqttConnection client = this.getConnection(clientHandle);
        client.unsubscribe(topic, invocationContext, activityToken);
    }

    public IMqttDeliveryToken[] getPendingDeliveryTokens(String clientHandle) {
        MqttConnection client = this.getConnection(clientHandle);
        return client.getPendingDeliveryTokens();
    }

    private MqttConnection getConnection(String clientHandle) {
        MqttConnection client = (MqttConnection)this.connections.get(clientHandle);
        if (client == null) {
            throw new IllegalArgumentException("Invalid ClientHandle");
        } else {
            return client;
        }
    }

    public Status acknowledgeMessageArrival(String clientHandle, String id) {
        return this.messageStore.discardArrived(clientHandle, id) ? Status.OK : Status.ERROR;
    }

    public void onCreate() {
        super.onCreate();
        this.mqttServiceBinder = new MqttServiceBinder(this);
        this.messageStore = new DatabaseMessageStore(this, this);
    }

    public void onDestroy() {
        Iterator i$ = this.connections.values().iterator();

        while(i$.hasNext()) {
            MqttConnection client = (MqttConnection)i$.next();
            client.disconnect((String)null, (String)null);
        }

        if (this.mqttServiceBinder != null) {
            this.mqttServiceBinder = null;
        }

        this.unregisterBroadcastReceivers();
        if (this.messageStore != null) {
            this.messageStore.close();
        }

        super.onDestroy();
    }

    public IBinder onBind(Intent intent) {
        String activityToken = intent.getStringExtra("MqttService.activityToken");
        this.mqttServiceBinder.setActivityToken(activityToken);
        return this.mqttServiceBinder;
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        this.registerBroadcastReceivers();
        return Service.START_STICKY;
    }

    public void setTraceCallbackId(String traceCallbackId) {
        this.traceCallbackId = traceCallbackId;
    }

    public void setTraceEnabled(boolean traceEnabled) {
        this.traceEnabled = traceEnabled;
    }

    public boolean isTraceEnabled() {
        return this.traceEnabled;
    }

    public void traceDebug(String tag, String message) {
        this.traceCallback("debug", tag, message);
    }

    public void traceError(String tag, String message) {
        this.traceCallback("error", tag, message);
    }

    private void traceCallback(String severity, String tag, String message) {
        if (this.traceCallbackId != null && this.traceEnabled) {
            Bundle dataBundle = new Bundle();
            dataBundle.putString("MqttService.callbackAction", "trace");
            dataBundle.putString("MqttService.traceSeverity", severity);
            dataBundle.putString("MqttService.traceTag", tag);
            dataBundle.putString("MqttService.errorMessage", message);
            this.callbackToActivity(this.traceCallbackId, Status.ERROR, dataBundle);
        }

    }

    public void traceException(String tag, String message, Exception e) {
        if (this.traceCallbackId != null) {
            Bundle dataBundle = new Bundle();
            dataBundle.putString("MqttService.callbackAction", "trace");
            dataBundle.putString("MqttService.traceSeverity", "exception");
            dataBundle.putString("MqttService.errorMessage", message);
            dataBundle.putSerializable("MqttService.exception", e);
            dataBundle.putString("MqttService.traceTag", tag);
            this.callbackToActivity(this.traceCallbackId, Status.ERROR, dataBundle);
        }

    }

    private void registerBroadcastReceivers() {
        if (this.networkConnectionMonitor == null) {
            this.networkConnectionMonitor = new MqttService.NetworkConnectionIntentReceiver();
            this.registerReceiver(this.networkConnectionMonitor, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
        }

        if (Build.VERSION.SDK_INT < 14) {
            ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
            this.backgroundDataEnabled = cm.getBackgroundDataSetting();
            if (this.backgroundDataPreferenceMonitor == null) {
                this.backgroundDataPreferenceMonitor = new MqttService.BackgroundDataPreferenceReceiver();
                this.registerReceiver(this.backgroundDataPreferenceMonitor, new IntentFilter("android.net.conn.BACKGROUND_DATA_SETTING_CHANGED"));
            }
        }

    }

    private void unregisterBroadcastReceivers() {
        if (this.networkConnectionMonitor != null) {
            this.unregisterReceiver(this.networkConnectionMonitor);
            this.networkConnectionMonitor = null;
        }

        if (Build.VERSION.SDK_INT < 14 && this.backgroundDataPreferenceMonitor != null) {
            this.unregisterReceiver(this.backgroundDataPreferenceMonitor);
        }

    }

    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected() && this.backgroundDataEnabled;
    }

    public void notifyClientsOffline() {
        Iterator i$ = this.connections.values().iterator();

        while(i$.hasNext()) {
            MqttConnection connection = (MqttConnection)i$.next();
            connection.offline();
        }

    }

    public void setBufferOpts(String clientHandle, DisconnectedBufferOptions bufferOpts) {
        MqttConnection client = this.getConnection(clientHandle);
        client.setBufferOpts(bufferOpts);
    }

    public int getBufferedMessageCount(String clientHandle) {
        MqttConnection client = this.getConnection(clientHandle);
        return client.getBufferedMessageCount();
    }

    public MqttMessage getBufferedMessage(String clientHandle, int bufferIndex) {
        MqttConnection client = this.getConnection(clientHandle);
        return client.getBufferedMessage(bufferIndex);
    }

    public void deleteBufferedMessage(String clientHandle, int bufferIndex) {
        MqttConnection client = this.getConnection(clientHandle);
        client.deleteBufferedMessage(bufferIndex);
    }

    private class BackgroundDataPreferenceReceiver extends BroadcastReceiver {
        private BackgroundDataPreferenceReceiver() {
        }

        public void onReceive(Context context, Intent intent) {
            ConnectivityManager cm = (ConnectivityManager) MqttService.this.getSystemService(Context.CONNECTIVITY_SERVICE);
            MqttService.this.traceDebug("MqttService", "Reconnect since BroadcastReceiver.");
            if (cm.getBackgroundDataSetting()) {
                if (!MqttService.this.backgroundDataEnabled) {
                    MqttService.this.backgroundDataEnabled = true;
                    MqttService.this.reconnect();
                }
            } else {
                MqttService.this.backgroundDataEnabled = false;
                MqttService.this.notifyClientsOffline();
            }

        }
    }

    private class NetworkConnectionIntentReceiver extends BroadcastReceiver {
        private NetworkConnectionIntentReceiver() {
        }

        public void onReceive(Context context, Intent intent) {
            MqttService.this.traceDebug("MqttService", "Internal network status receive.");
            PowerManager pm = (PowerManager) MqttService.this.getSystemService(Context.POWER_SERVICE);
            WakeLock wl = pm.newWakeLock(1, "MQTT");
            wl.acquire();
            MqttService.this.traceDebug("MqttService", "Reconnect for Network recovery.");
            if (MqttService.this.isOnline()) {
                MqttService.this.traceDebug("MqttService", "Online,reconnect.");
                MqttService.this.reconnect();
            } else {
                MqttService.this.notifyClientsOffline();
            }

            wl.release();
        }
    }


}

MqttServiceBinder.java

package com.iot.listeninsoul.service;

import android.os.Binder;


class MqttServiceBinder  extends Binder {
   private MqttService mqttService;
   private String activityToken;

   MqttServiceBinder(MqttService mqttService) {
      this.mqttService = mqttService;
   }

   public MqttService getService() {
      return this.mqttService;
   }

   void setActivityToken(String activityToken) {
      this.activityToken = activityToken;
   }

   public String getActivityToken() {
      return this.activityToken;
   }
}

MqttServiceConstants.java

package com.iot.listeninsoul.service;

//edit
class MqttServiceConstants {
    String VERSION = "v0";
    String DUPLICATE = "duplicate";
    String RETAINED = "retained";
    String QOS = "qos";
    String PAYLOAD = "payload";
    String DESTINATION_NAME = "destinationName";
    String CLIENT_HANDLE = "clientHandle";
    String MESSAGE_ID = "messageId";
    String SEND_ACTION = "send";
    String UNSUBSCRIBE_ACTION = "unsubscribe";
    String SUBSCRIBE_ACTION = "subscribe";
    String DISCONNECT_ACTION = "disconnect";
    String CONNECT_ACTION = "connect";
    String CONNECT_EXTENDED_ACTION = "connectExtended";
    String MESSAGE_ARRIVED_ACTION = "messageArrived";
    String MESSAGE_DELIVERED_ACTION = "messageDelivered";
    String ON_CONNECTION_LOST_ACTION = "onConnectionLost";
    String TRACE_ACTION = "trace";
    String CALLBACK_TO_ACTIVITY = "MqttService.callbackToActivity.v0";
    String CALLBACK_ACTION = "MqttService.callbackAction";
    String CALLBACK_STATUS = "MqttService.callbackStatus";
    String CALLBACK_CLIENT_HANDLE = "MqttService.clientHandle";
    String CALLBACK_ERROR_MESSAGE = "MqttService.errorMessage";
    String CALLBACK_EXCEPTION_STACK = "MqttService.exceptionStack";
    String CALLBACK_INVOCATION_CONTEXT = "MqttService.invocationContext";
    String CALLBACK_ACTIVITY_TOKEN = "MqttService.activityToken";
    String CALLBACK_DESTINATION_NAME = "MqttService.destinationName";
    String CALLBACK_MESSAGE_ID = "MqttService.messageId";
    String CALLBACK_RECONNECT = "MqttService.reconnect";
    String CALLBACK_SERVER_URI = "MqttService.serverURI";
    String CALLBACK_MESSAGE_PARCEL = "MqttService.PARCEL";
    String CALLBACK_TRACE_SEVERITY = "MqttService.traceSeverity";
    String CALLBACK_TRACE_TAG = "MqttService.traceTag";
    String CALLBACK_TRACE_ID = "MqttService.traceId";
    String CALLBACK_ERROR_NUMBER = "MqttService.ERROR_NUMBER";
    String CALLBACK_EXCEPTION = "MqttService.exception";
    String PING_SENDER = "MqttService.pingSender.";
    String PING_WAKELOCK = "MqttService.client.";
    String WAKELOCK_NETWORK_INTENT = "MqttService";
    String TRACE_ERROR = "error";
    String TRACE_DEBUG = "debug";
    String TRACE_EXCEPTION = "exception";
    int NON_MQTT_EXCEPTION = -1;
}

MqttTokenAndroid.java

package com.iot.listeninsoul.service;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttAsyncClient;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.internal.wire.MqttWireMessage;

class MqttTokenAndroid implements IMqttToken {
   private IMqttActionListener listener;
   private volatile boolean isComplete;
   private volatile MqttException lastException;
   private Object waitObject;
   private MqttAndroidClient client;
   private Object userContext;
   private String[] topics;
   private IMqttToken delegate;
   private MqttException pendingException;

   MqttTokenAndroid(MqttAndroidClient client, Object userContext, IMqttActionListener listener) {
      this(client, userContext, listener, (String[])null);
   }

   MqttTokenAndroid(MqttAndroidClient client, Object userContext, IMqttActionListener listener, String[] topics) {
      this.waitObject = new Object();
      this.client = client;
      this.userContext = userContext;
      this.listener = listener;
      this.topics = topics;
   }

   public void waitForCompletion() throws MqttException, MqttSecurityException {
      synchronized(this.waitObject) {
         try {
            this.waitObject.wait();
         } catch (InterruptedException var4) {
         }
      }

      if (this.pendingException != null) {
         throw this.pendingException;
      }
   }

   public void waitForCompletion(long timeout) throws MqttException, MqttSecurityException {
      synchronized(this.waitObject) {
         try {
            this.waitObject.wait(timeout);
         } catch (InterruptedException var6) {
         }

         if (!this.isComplete) {
            throw new MqttException(32000);
         } else if (this.pendingException != null) {
            throw this.pendingException;
         }
      }
   }

   void notifyComplete() {
      synchronized(this.waitObject) {
         this.isComplete = true;
         this.waitObject.notifyAll();
         if (this.listener != null) {
            this.listener.onSuccess(this);
         }

      }
   }

   void notifyFailure(Throwable exception) {
      synchronized(this.waitObject) {
         this.isComplete = true;
         if (exception instanceof MqttException) {
            this.pendingException = (MqttException)exception;
         } else {
            this.pendingException = new MqttException(exception);
         }

         this.waitObject.notifyAll();
         if (exception instanceof MqttException) {
            this.lastException = (MqttException)exception;
         }

         if (this.listener != null) {
            this.listener.onFailure(this, exception);
         }

      }
   }

   public boolean isComplete() {
      return this.isComplete;
   }

   void setComplete(boolean complete) {
      this.isComplete = complete;
   }

   public MqttException getException() {
      return this.lastException;
   }

   void setException(MqttException exception) {
      this.lastException = exception;
   }

   public IMqttAsyncClient getClient() {
      return this.client;
   }

   public void setActionCallback(IMqttActionListener listener) {
      this.listener = listener;
   }

   public IMqttActionListener getActionCallback() {
      return this.listener;
   }

   public String[] getTopics() {
      return this.topics;
   }

   public void setUserContext(Object userContext) {
      this.userContext = userContext;
   }

   public Object getUserContext() {
      return this.userContext;
   }

   void setDelegate(IMqttToken delegate) {
      this.delegate = delegate;
   }

   public int getMessageId() {
      return this.delegate != null ? this.delegate.getMessageId() : 0;
   }

   public MqttWireMessage getResponse() {
      return this.delegate.getResponse();
   }

   public boolean getSessionPresent() {
      return this.delegate.getSessionPresent();
   }

   public int[] getGrantedQos() {
      return this.delegate.getGrantedQos();
   }
}

MqttTraceHandler.java

package com.iot.listeninsoul.service;

/**
 * Interface for simple trace handling, pass the trace message to trace
 * callback.
 */
//edit
public interface MqttTraceHandler {

	void traceDebug(String var1, String var2);

	void traceError(String var1, String var2);

	void traceException(String var1, String var2, Exception var3);

}

ParcelableMqttMessage.java

package com.iot.listeninsoul.service;

import android.os.Parcel;
import android.os.Parcelable;

import org.eclipse.paho.client.mqttv3.MqttMessage;


//edit
class ParcelableMqttMessage extends MqttMessage implements Parcelable {
    String messageId = null;
    public static final Creator<ParcelableMqttMessage> CREATOR = new Creator<ParcelableMqttMessage>() {
        public ParcelableMqttMessage createFromParcel(Parcel parcel) {
            return new ParcelableMqttMessage(parcel);
        }

        public ParcelableMqttMessage[] newArray(int size) {
            return new ParcelableMqttMessage[size];
        }
    };

    ParcelableMqttMessage(MqttMessage original) {
        super(original.getPayload());
        this.setQos(original.getQos());
        this.setRetained(original.isRetained());
        this.setDuplicate(original.isDuplicate());
    }

    ParcelableMqttMessage(Parcel parcel) {
        super(parcel.createByteArray());
        this.setQos(parcel.readInt());
        boolean[] flags = parcel.createBooleanArray();
        this.setRetained(flags[0]);
        this.setDuplicate(flags[1]);
        this.messageId = parcel.readString();
    }

    public String getMessageId() {
        return this.messageId;
    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel parcel, int flags) {
        parcel.writeByteArray(this.getPayload());
        parcel.writeInt(this.getQos());
        parcel.writeBooleanArray(new boolean[]{this.isRetained(), this.isDuplicate()});
        parcel.writeString(this.messageId);
    }
}

Status.java

package com.iot.listeninsoul.service;

//edit
enum Status {
 OK,
 ERROR,
 NO_RESULT;

 private Status() {
 }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全面解读

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值