修改KTV房间编码模式
修改点唱房编码模式 优化展示麦位布局 优化Mqtt,变更成单例模式
This commit is contained in:
@@ -1,27 +1,20 @@
|
||||
package com.xscm.moduleutil.service;
|
||||
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ServiceInfo;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.net.NetworkInfo;
|
||||
import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.os.HandlerThread;
|
||||
import android.os.IBinder;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.blankj.utilcode.util.LogUtils;
|
||||
import com.blankj.utilcode.util.ServiceUtils;
|
||||
import com.orhanobut.logger.Logger;
|
||||
import com.xscm.moduleutil.R;
|
||||
import com.xscm.moduleutil.event.RoomGiftRunable;
|
||||
@@ -35,35 +28,32 @@ import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
|
||||
import org.eclipse.paho.client.mqttv3.MqttException;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
|
||||
public class MyMqttService extends Service implements MyEmqttConnectListener, MyEmqttMesgListener, MyEmqttSubscribeListener {
|
||||
public class MyMqttService implements MyEmqttConnectListener, MyEmqttMesgListener, MyEmqttSubscribeListener {
|
||||
|
||||
private final static String TAG = "lxj";
|
||||
|
||||
private static int qos = 2;
|
||||
// private static String HOST ="tcp://81.70.45.221";//正式
|
||||
private static String HOST = "tcp://1.13.181.248";//测试
|
||||
// private static String HOST = "tcp://47.120.21.132";//测试
|
||||
private static MqttAndroidClient mqttAndroidClient;
|
||||
private MqttConnectOptions mMqttConnectOptions;
|
||||
private static boolean b = true;
|
||||
|
||||
// 使用单例模式
|
||||
private static MyMqttService instance;
|
||||
|
||||
private static MyEmqttConnectListener mMyEmqttConnectListener;
|
||||
private static MyEmqttMesgListener mMyEmqttMesgListener;
|
||||
private static MyEmqttSubscribeListener mMyEmqttSubscribeListener;
|
||||
// 使用线程安全的集合存储监听器
|
||||
private static final CopyOnWriteArrayList<MyEmqttMesgListener> messageListeners = new CopyOnWriteArrayList<>();
|
||||
private static final CopyOnWriteArrayList<MyEmqttConnectListener> connectListeners = new CopyOnWriteArrayList<>();
|
||||
private static final CopyOnWriteArrayList<MyEmqttSubscribeListener> subscribeListeners = new CopyOnWriteArrayList<>();
|
||||
|
||||
private static final String TOPIC_BOSS = "qx_room_topic";
|
||||
|
||||
private static final String TOPIC_XLH = "qx_xunlehui";
|
||||
private static final int NOTIFICATION_ID = 1;
|
||||
|
||||
|
||||
// 添加后台线程处理
|
||||
private HandlerThread mqttHandlerThread;
|
||||
@@ -74,27 +64,31 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
private static final int MAX_RETRY_ATTEMPTS = 5;
|
||||
private int retryCount = 0;
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { // API 31+
|
||||
// 设置前台服务类型为 "connectedDevice" 或其他合适类型
|
||||
setForegroundServiceBehavior(ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST);
|
||||
// 服务状态
|
||||
private static boolean isServiceRunning = false;
|
||||
|
||||
private Context mContext;
|
||||
|
||||
// 私有构造函数
|
||||
private MyMqttService(Context context) {
|
||||
this.mContext = context.getApplicationContext();
|
||||
initService();
|
||||
}
|
||||
|
||||
public static MyMqttService getInstance(Context context) {
|
||||
if (instance == null) {
|
||||
synchronized (MyMqttService.class) {
|
||||
if (instance == null) {
|
||||
instance = new MyMqttService(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
// ⚠️ 必须在这个方法开始就调用 startForeground()
|
||||
Notification notification = createNotification();
|
||||
startForeground(NOTIFICATION_ID, notification);
|
||||
|
||||
return START_STICKY;
|
||||
return instance;
|
||||
}
|
||||
|
||||
private void setForegroundServiceBehavior(int foregroundServiceTypeManifest) {
|
||||
// 空实现,仅用于兼容性处理
|
||||
}
|
||||
private void initService() {
|
||||
isServiceRunning = true;
|
||||
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
// 创建专用的HandlerThread处理MQTT操作
|
||||
mqttHandlerThread = new HandlerThread("MqttServiceThread");
|
||||
mqttHandlerThread.start();
|
||||
@@ -105,77 +99,127 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
try {
|
||||
init();
|
||||
} catch (MqttException e) {
|
||||
throw new RuntimeException(e);
|
||||
Log.e(TAG, "MQTT初始化异常", e);
|
||||
}
|
||||
}
|
||||
|
||||
private Notification createNotification() {
|
||||
// 创建你的前台通知
|
||||
// Notification.Builder builder = null;
|
||||
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
// builder = new Notification.Builder(this, "channel_id")
|
||||
// .setContentTitle("MQTT Service")
|
||||
// .setSmallIcon(R.mipmap.default_avatar);
|
||||
// }
|
||||
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
// NotificationChannel channel = new NotificationChannel(
|
||||
// "channel_id", "MQTT Channel",
|
||||
// NotificationManager.IMPORTANCE_LOW);
|
||||
// NotificationManager manager = getSystemService(NotificationManager.class);
|
||||
// manager.createNotificationChannel(channel);
|
||||
// }
|
||||
// return builder.build();
|
||||
|
||||
// 创建你的前台通知
|
||||
Notification.Builder builder = null;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
builder = new Notification.Builder(this, "mqtt_channel")
|
||||
.setContentTitle("消息服务")
|
||||
.setContentText("正在接收实时消息")
|
||||
.setSmallIcon(R.mipmap.default_avatar);
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
NotificationChannel channel = new NotificationChannel(
|
||||
"mqtt_channel", "MQTT Channel",
|
||||
NotificationManager.IMPORTANCE_LOW);
|
||||
NotificationManager manager = getSystemService(NotificationManager.class);
|
||||
if (manager != null) {
|
||||
manager.createNotificationChannel(channel);
|
||||
}
|
||||
}
|
||||
return builder != null ? builder.build() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 开启服务
|
||||
* 启动MQTT连接
|
||||
*/
|
||||
public static void startService(Context mContext) {
|
||||
public void startService() {
|
||||
b = true;
|
||||
boolean serviceRunning = ServiceUtils.isServiceRunning(MyMqttService.class.getCanonicalName());
|
||||
if (!serviceRunning) {
|
||||
mContext.startService(new Intent(mContext, MyMqttService.class));
|
||||
if (!isServiceRunning) {
|
||||
initService();
|
||||
}
|
||||
}
|
||||
|
||||
public static void stopService(Context context) {
|
||||
/**
|
||||
* 停止MQTT服务
|
||||
*/
|
||||
public void stopService() {
|
||||
b = false;
|
||||
boolean serviceRunning = ServiceUtils.isServiceRunning(MyMqttService.class.getCanonicalName());
|
||||
if (serviceRunning) {
|
||||
try {
|
||||
context.stopService(new Intent(context, MyMqttService.class));
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to stop MQTT service", e);
|
||||
}
|
||||
isServiceRunning = false;
|
||||
cleanup();
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化
|
||||
*/
|
||||
private void init() throws MqttException {
|
||||
String CLIENTID = "android-" + MqttClient.generateClientId();
|
||||
mqttAndroidClient = new MqttAndroidClient(mContext, HOST, CLIENTID);
|
||||
mqttAndroidClient.setCallback(mqttCallback); //设置监听订阅消息的回调
|
||||
mMqttConnectOptions = new MqttConnectOptions();
|
||||
mMqttConnectOptions.setCleanSession(true); //设置是否清除缓存
|
||||
mMqttConnectOptions.setConnectionTimeout(10); //设置超时时间,单位:秒
|
||||
mMqttConnectOptions.setKeepAliveInterval(10); //设置心跳包发送间隔,单位:秒
|
||||
mMqttConnectOptions.setUserName("public"); //设置用户名
|
||||
mMqttConnectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
|
||||
|
||||
if (mqttAndroidClient != null && !mqttAndroidClient.isConnected()) {
|
||||
doClientConnection();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
private void doClientConnection() throws MqttException {
|
||||
// 在后台线程执行连接操作
|
||||
mqttHandler.post(() -> {
|
||||
if (mqttAndroidClient != null && !mqttAndroidClient.isConnected() && isConnectIsNomarl() && b) {
|
||||
try {
|
||||
mqttAndroidClient.connect(mMqttConnectOptions, null, iMqttActionListener);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "MQTT连接异常", e);
|
||||
handleConnectionFailure();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void handleConnectionFailure() {
|
||||
retryCount++;
|
||||
if (retryCount < MAX_RETRY_ATTEMPTS) {
|
||||
// 延迟重试
|
||||
mqttHandler.postDelayed(() -> {
|
||||
if (b) {
|
||||
try {
|
||||
doClientConnection();
|
||||
} catch (MqttException e) {
|
||||
Log.e(TAG, "MQTT连接异常", e);
|
||||
}
|
||||
}
|
||||
}, 5000); // 5秒后重试
|
||||
} else {
|
||||
Log.w(TAG, "达到最大重试次数,停止重试");
|
||||
retryCount = 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static void closeConnection() {
|
||||
Handler handler = new Handler(Looper.getMainLooper());
|
||||
handler.post(() -> {
|
||||
try {
|
||||
if (mqttAndroidClient != null && mqttAndroidClient.isConnected()) {
|
||||
IMqttToken disconnect = mqttAndroidClient.disconnect();
|
||||
disconnect.setActionCallback(new IMqttActionListener() {
|
||||
@Override
|
||||
public void onSuccess(IMqttToken asyncActionToken) {
|
||||
Logger.e(TAG, "断开链接", "断开链接成功");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
|
||||
Logger.e(TAG, "断开链接", "断开链接失败" + exception.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "关闭连接异常", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断网络是否连接
|
||||
*/
|
||||
private boolean isConnectIsNomarl() {
|
||||
try {
|
||||
ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
if (connectivityManager != null) {
|
||||
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
|
||||
if (info != null && info.isAvailable()) {
|
||||
String name = info.getTypeName();
|
||||
Log.i(TAG, "当前网络名称:" + name);
|
||||
return true;
|
||||
} else {
|
||||
Log.i(TAG, "没有可用网络");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "检查网络状态异常", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布 (模拟其他客户端发布消息)
|
||||
@@ -221,8 +265,10 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
subToken.setActionCallback(new IMqttActionListener() {
|
||||
@Override
|
||||
public void onSuccess(IMqttToken asyncActionToken) {
|
||||
if (mMyEmqttSubscribeListener != null) {
|
||||
mMyEmqttSubscribeListener.onSubscribeSuccess(topic);
|
||||
for (MyEmqttSubscribeListener listener : subscribeListeners) {
|
||||
if (listener != null) {
|
||||
listener.onSubscribeSuccess(topic);
|
||||
}
|
||||
}
|
||||
Logger.e(TAG, "订阅成功:" + topic);
|
||||
}
|
||||
@@ -230,9 +276,12 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
@Override
|
||||
public void onFailure(IMqttToken asyncActionToken,
|
||||
Throwable exception) {
|
||||
if ((!TOPIC_BOSS.equals(topic) && mMyEmqttSubscribeListener != null)
|
||||
|| (!TOPIC_XLH.equals(topic) && mMyEmqttSubscribeListener != null)) {
|
||||
mMyEmqttSubscribeListener.onSubscribeFailure();
|
||||
for (MyEmqttSubscribeListener listener : subscribeListeners) {
|
||||
if (listener != null &&
|
||||
!TOPIC_BOSS.equals(topic) &&
|
||||
!TOPIC_XLH.equals(topic)) {
|
||||
listener.onSubscribeFailure();
|
||||
}
|
||||
}
|
||||
Logger.e(TAG, "订阅失败:" + topic + ", error: " + exception.getMessage());
|
||||
}
|
||||
@@ -270,118 +319,20 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 初始化
|
||||
*/
|
||||
private void init() throws MqttException {
|
||||
String CLIENTID = "android-" + MqttClient.generateClientId();
|
||||
mqttAndroidClient = new MqttAndroidClient(this, HOST, CLIENTID);
|
||||
mqttAndroidClient.setCallback(mqttCallback); //设置监听订阅消息的回调
|
||||
mMqttConnectOptions = new MqttConnectOptions();
|
||||
mMqttConnectOptions.setCleanSession(true); //设置是否清除缓存
|
||||
mMqttConnectOptions.setConnectionTimeout(10); //设置超时时间,单位:秒
|
||||
mMqttConnectOptions.setKeepAliveInterval(10); //设置心跳包发送间隔,单位:秒
|
||||
mMqttConnectOptions.setUserName("public"); //设置用户名
|
||||
// mMqttConnectOptions.setPassword(new char[0]); //设置密码
|
||||
mMqttConnectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
|
||||
|
||||
if (mqttAndroidClient != null && !mqttAndroidClient.isConnected()) {
|
||||
doClientConnection();
|
||||
}
|
||||
}
|
||||
|
||||
private void doClientConnection() throws MqttException {
|
||||
// 在后台线程执行连接操作
|
||||
mqttHandler.post(() -> {
|
||||
if (mqttAndroidClient != null && !mqttAndroidClient.isConnected() && isConnectIsNomarl() && b) {
|
||||
try {
|
||||
mqttAndroidClient.connect(mMqttConnectOptions, null, iMqttActionListener);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "MQTT连接异常", e);
|
||||
handleConnectionFailure();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void handleConnectionFailure() {
|
||||
retryCount++;
|
||||
if (retryCount < MAX_RETRY_ATTEMPTS) {
|
||||
// 延迟重试
|
||||
mqttHandler.postDelayed(() -> {
|
||||
if (b) {
|
||||
try {
|
||||
doClientConnection();
|
||||
} catch (MqttException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}, 5000); // 5秒后重试
|
||||
} else {
|
||||
Log.w(TAG, "达到最大重试次数,停止重试");
|
||||
retryCount = 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static void closeConnection() {
|
||||
Handler handler = new Handler(Looper.getMainLooper());
|
||||
handler.post(() -> {
|
||||
try {
|
||||
if (mqttAndroidClient != null && mqttAndroidClient.isConnected()) {
|
||||
IMqttToken disconnect = mqttAndroidClient.disconnect();
|
||||
disconnect.setActionCallback(new IMqttActionListener() {
|
||||
@Override
|
||||
public void onSuccess(IMqttToken asyncActionToken) {
|
||||
Logger.e(TAG, "断开链接", "断开链接成功");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
|
||||
Logger.e(TAG, "断开链接", "断开链接失败" + exception.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "关闭连接异常", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 判断网络是否连接
|
||||
*/
|
||||
private boolean isConnectIsNomarl() {
|
||||
try {
|
||||
ConnectivityManager connectivityManager = (ConnectivityManager) this.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
if (connectivityManager != null) {
|
||||
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
|
||||
if (info != null && info.isAvailable()) {
|
||||
String name = info.getTypeName();
|
||||
Log.i(TAG, "当前网络名称:" + name);
|
||||
return true;
|
||||
} else {
|
||||
Log.i(TAG, "没有可用网络");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "检查网络状态异常", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
//MQTT是否连接成功的监听
|
||||
private IMqttActionListener iMqttActionListener = new IMqttActionListener() {
|
||||
|
||||
@Override
|
||||
public void onSuccess(IMqttToken arg0) {
|
||||
retryCount = 0; // 重置重试计数
|
||||
if (mMyEmqttConnectListener != null) {
|
||||
mMyEmqttConnectListener.onConnectSuccess();
|
||||
|
||||
// 通知所有连接监听器
|
||||
for (MyEmqttConnectListener listener : connectListeners) {
|
||||
if (listener != null) {
|
||||
listener.onConnectSuccess();
|
||||
}
|
||||
}
|
||||
|
||||
Logger.e(TAG, "链接状态:", "链接成功");
|
||||
subscribe(TOPIC_BOSS);
|
||||
subscribe(TOPIC_XLH);
|
||||
@@ -389,12 +340,15 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
|
||||
@Override
|
||||
public void onFailure(IMqttToken arg0, Throwable arg1) {
|
||||
if (mMyEmqttConnectListener != null) {
|
||||
mMyEmqttConnectListener.onConnectFailure();
|
||||
// 通知所有连接监听器
|
||||
for (MyEmqttConnectListener listener : connectListeners) {
|
||||
if (listener != null) {
|
||||
listener.onConnectFailure();
|
||||
}
|
||||
}
|
||||
// if (arg0 instanceof MqttException) {
|
||||
//// Logger.e(TAG, "链接状态:", "链接失败" + ((MqttException) arg1).getMessage());
|
||||
// }
|
||||
|
||||
Logger.e(TAG, "链接状态:", "链接失败: " + arg1.getMessage());
|
||||
|
||||
// 在后台线程处理重连
|
||||
mqttHandler.postDelayed(() -> {
|
||||
if (b) {
|
||||
@@ -404,7 +358,6 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
//订阅主题的回调
|
||||
private MqttCallback mqttCallback = new MqttCallback() {
|
||||
|
||||
@@ -417,23 +370,29 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
Logger.e(TAG, "收到的消息", "主题:" + topic + " 收到的消息:" + messageStr);
|
||||
if (topic.equals(TOPIC_BOSS)) {
|
||||
// 处理消息
|
||||
receiveMessage(topic, messageStr);
|
||||
|
||||
// receiveMessage(topic, messageStr);
|
||||
// new Handler(Looper.getMainLooper()).post(() -> {
|
||||
receiveMessage(topic, messageStr);
|
||||
// });
|
||||
// 通知监听器
|
||||
if (mMyEmqttMesgListener != null) {
|
||||
// 切换到主线程通知
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
mMyEmqttMesgListener.messageArrived(topic, messageStr);
|
||||
});
|
||||
}
|
||||
// for (MyEmqttMesgListener listener : messageListeners) {
|
||||
// if (listener != null) {
|
||||
// // 切换到主线程通知
|
||||
//// new Handler(Looper.getMainLooper()).post(() -> {
|
||||
////// listener.messageArrived(topic, messageStr);
|
||||
//// });
|
||||
// }
|
||||
// }
|
||||
} else if (topic.equals(TOPIC_XLH)) {
|
||||
receiveXlhMessage(messageStr);
|
||||
// receiveXlhMessage(messageStr);
|
||||
// new Handler(Looper.getMainLooper()).post(() -> {
|
||||
receiveXlhMessage(messageStr);
|
||||
// });
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "处理MQTT消息异常", e);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -443,9 +402,13 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
|
||||
@Override
|
||||
public void connectionLost(Throwable arg0) {
|
||||
if (mMyEmqttConnectListener != null) {
|
||||
mMyEmqttConnectListener.onConnectFailure();
|
||||
// 通知所有连接监听器
|
||||
for (MyEmqttConnectListener listener : connectListeners) {
|
||||
if (listener != null) {
|
||||
listener.onConnectFailure();
|
||||
}
|
||||
}
|
||||
|
||||
Logger.e(TAG, "链接状态:", "链接断开: " + arg0.getMessage());
|
||||
|
||||
// 在后台线程处理重连
|
||||
@@ -454,7 +417,7 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
try {
|
||||
doClientConnection();
|
||||
} catch (MqttException e) {
|
||||
throw new RuntimeException(e);
|
||||
Log.e(TAG, "MQTT连接异常", e);
|
||||
}
|
||||
}
|
||||
}, 1000);
|
||||
@@ -463,14 +426,12 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
|
||||
private void receiveXlhMessage(String messageStr) {
|
||||
try {
|
||||
String newdata = messageStr;//TextLengthUtil.decode(data);
|
||||
String newdata = messageStr;
|
||||
JSONObject jsonObject = JSON.parseObject(newdata);
|
||||
|
||||
int type = jsonObject.getIntValue("type");
|
||||
String message = jsonObject.getString("msg");
|
||||
|
||||
|
||||
|
||||
// 将事件处理放到主线程执行
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
processMessageType(type, message);
|
||||
@@ -482,7 +443,7 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
|
||||
private void receiveMessage(String topic, String data) {
|
||||
try {
|
||||
String newdata = data;//TextLengthUtil.decode(data);
|
||||
String newdata = data;
|
||||
JSONObject jsonObject = JSON.parseObject(newdata);
|
||||
|
||||
int type = jsonObject.getIntValue("type");
|
||||
@@ -644,10 +605,10 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
b = false;
|
||||
|
||||
/**
|
||||
* 清理资源
|
||||
*/
|
||||
public void cleanup() {
|
||||
try {
|
||||
// 清理资源
|
||||
if (messageExecutorService != null) {
|
||||
@@ -658,6 +619,7 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
messageExecutorService.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -672,51 +634,65 @@ public class MyMqttService extends Service implements MyEmqttConnectListener, My
|
||||
mqttAndroidClient.unregisterResources();
|
||||
mqttAndroidClient = null;
|
||||
}
|
||||
stopForeground(true); // 停止前台服务
|
||||
Logger.e(TAG, "服务关闭", "资源释放成功");
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "服务关闭异常", e);
|
||||
}
|
||||
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
|
||||
// 修改监听器管理方法
|
||||
public static void addMyEmqttMesgListener(MyEmqttMesgListener myEmqttMesgListener) {
|
||||
mMyEmqttMesgListener = myEmqttMesgListener;
|
||||
if (myEmqttMesgListener != null && !messageListeners.contains(myEmqttMesgListener)) {
|
||||
messageListeners.add(myEmqttMesgListener);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeMyEmqttMesgListener(MyEmqttMesgListener myEmqttMesgListener) {
|
||||
messageListeners.remove(myEmqttMesgListener);
|
||||
}
|
||||
|
||||
public static void addMyEmqttConnectListener(MyEmqttConnectListener myEmqttConnectListener) {
|
||||
mMyEmqttConnectListener = myEmqttConnectListener;
|
||||
if (myEmqttConnectListener != null && !connectListeners.contains(myEmqttConnectListener)) {
|
||||
connectListeners.add(myEmqttConnectListener);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeMyEmqttConnectListener(MyEmqttConnectListener myEmqttConnectListener) {
|
||||
connectListeners.remove(myEmqttConnectListener);
|
||||
}
|
||||
|
||||
public static void addMyEmqttSubscribeListener(MyEmqttSubscribeListener myEmqttSubscribeListener) {
|
||||
mMyEmqttSubscribeListener = myEmqttSubscribeListener;
|
||||
if (myEmqttSubscribeListener != null && !subscribeListeners.contains(myEmqttSubscribeListener)) {
|
||||
subscribeListeners.add(myEmqttSubscribeListener);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeMyEmqttSubscribeListener(MyEmqttSubscribeListener myEmqttSubscribeListener) {
|
||||
subscribeListeners.remove(myEmqttSubscribeListener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConnectSuccess() {
|
||||
|
||||
// 实现接口方法
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConnectFailure() {
|
||||
|
||||
// 实现接口方法
|
||||
}
|
||||
|
||||
@Override
|
||||
public void messageArrived(String topic, String mesg) {
|
||||
LogUtils.e("lxj", "messageArrived:"+mesg);
|
||||
LogUtils.e("lxj", "messageArrived:" + mesg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSubscribeSuccess(String topic) {
|
||||
LogUtils.e("lxj", "onSubscribeSuccess:"+topic);
|
||||
LogUtils.e("lxj", "onSubscribeSuccess:" + topic);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSubscribeFailure() {
|
||||
LogUtils.e("lxj", "onSubscribeFailure");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user