依赖包:
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0' implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
MqttService,主要功能,连接mqtt服务器,验证用户名密码,订阅Topic,回调接收到的mqtt消息
import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Binder; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.geti.switchcabinet.R; import com.geti.switchcabinet.application.App; import com.geti.switchcabinet.constant.MqttTopics; import com.geti.switchcabinet.mqttevent.MqttConnectEvent; import com.geti.switchcabinet.mqttevent.MqttSubscribeEvent; import com.geti.switchcabinet.util.SaveLogUtil; import org.eclipse.paho.android.service.MqttAndroidClient; import org.eclipse.paho.client.mqttv3.IMqttActionListener; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.greenrobot.eventbus.EventBus; public class MQTTService extends Service { public static final String TAG = MQTTService.class.getSimpleName(); private static MqttAndroidClient client; private MqttConnectOptions conOpt; private String clientId = "androidId";//客户端标识 private IGetMessageCallBack IGetMessageCallBack; @Override public void onCreate() { super.onCreate(); SaveLogUtil.saveLog(getClass().getName(), "onCreate"); init(); } public static void publish(String topic,String msg){ Integer qos = 0; Boolean retained = false; try { if (client != null){ client.publish(topic, msg.getBytes(), qos.intValue(), retained.booleanValue()); } } catch (MqttException e) { e.printStackTrace(); } } private void init() { // 服务器地址(协议+地址+端口号) String uri = App.MQTT_HOST; client = new MqttAndroidClient(this, uri, clientId); // 设置MQTT监听并且接受消息 client.setCallback(mqttCallback); conOpt = new MqttConnectOptions(); // 清除缓存 conOpt.setCleanSession(true); // 设置超时时间,单位:秒 conOpt.setConnectionTimeout(10); // 心跳包发送间隔,单位:秒 conOpt.setKeepAliveInterval(20); // 用户名 conOpt.setUserName(App.MQTT_USER);//mqtt用户名 可以全局可以写死 // 密码 conOpt.setPassword(App.MQTT_PWD.toCharArray()); //mqtt用户密码,全局或者写死,将字符串转换为字符串数组 doClientConnection(); } @Override public void onDestroy() { stopSelf(); try { client.disconnect(); } catch (MqttException e) { e.printStackTrace(); } super.onDestroy(); } /** 连接MQTT服务器 */ private void doClientConnection() { if (!client.isConnected() && isConnectIsNormal()) { try { client.connect(conOpt, null, iMqttActionListener); } catch (MqttException e) { e.printStackTrace(); } } } // MQTT是否连接成功,订阅需要的Topic private IMqttActionListener iMqttActionListener = new IMqttActionListener() { @Override public void onSuccess(IMqttToken arg0) { SaveLogUtil.saveLog(TAG, "连接成功 "); try { // 订阅myTopic话题 client.subscribe(MqttTopics.AllSubscribeTopics,new int[]{1,1,1,1,1},null,mqttActionListener); EventBus.getDefault().post(new MqttConnectEvent(true)); } catch (MqttException e) { e.printStackTrace(); } } @Override public void onFailure(IMqttToken arg0, Throwable arg1) { arg1.printStackTrace(); EventBus.getDefault().post(new MqttConnectEvent(false)); // 连接失败,重连 } }; // MQTT监听并且接受消息 private MqttCallback mqttCallback = new MqttCallback() { @Override public void messageArrived(String topic, MqttMessage message) throws Exception { String str1 = new String(message.getPayload()); if (IGetMessageCallBack != null){ IGetMessageCallBack.setMessage(str1); } String str2 = topic + ";qos:" + message.getQos() + ";retained:" + message.isRetained(); SaveLogUtil.saveLog(TAG, "==收到MQTT消息1==:" + str1+"=="+str2); } @Override public void deliveryComplete(IMqttDeliveryToken arg0) { } @Override public void connectionLost(Throwable arg0) { // 失去连接,重连 EventBus.getDefault().post(new MqttConnectEvent(false)); } }; private IMqttActionListener mqttActionListener = new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { EventBus.getDefault().post(new MqttSubscribeEvent(asyncActionToken.getTopics()[0],false)); } }; /** 判断网络是否连接 */ private boolean isConnectIsNormal() { ConnectivityManager connectivityManager = (ConnectivityManager) this.getApplicationContext() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = connectivityManager.getActiveNetworkInfo(); if (info != null && info.isAvailable()) { String name = info.getTypeName(); SaveLogUtil.saveLog(TAG, "==MQTT当前网络名称==" + name); return true; } else { SaveLogUtil.saveLog(TAG, "==MQTT 没有可用网络=="); return false; } } @Override public IBinder onBind(Intent intent) { SaveLogUtil.saveLog(getClass().getName(), "==onBind=="); return new CustomBinder(); } public void setIGetMessageCallBack(IGetMessageCallBack IGetMessageCallBack){ this.IGetMessageCallBack = IGetMessageCallBack; } public class CustomBinder extends Binder { public MQTTService getService(){ return MQTTService.this; } } }
Mqtt消息回调,也可以用 EventBus 代替
public interface IGetMessageCallBack { public void setMessage(String message); }
ServiceConnection,不用说
public class MyServiceConnection implements ServiceConnection { private MQTTService mqttService; private IGetMessageCallBack IGetMessageCallBack; @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { mqttService = ((MQTTService.CustomBinder)iBinder).getService(); mqttService.setIGetMessageCallBack(IGetMessageCallBack); } @Override public void onServiceDisconnected(ComponentName componentName) { } public MQTTService getMqttService(){ return mqttService; } public void setIGetMessageCallBack(IGetMessageCallBack IGetMessageCallBack){ this.IGetMessageCallBack = IGetMessageCallBack; } }
Activity中初始化
1.初始化主题,好在mqttservice 初始化后直接订阅这些主题,也可以根据需要修改
2.启动连接mqtt,启动mqttservice 来连接mqtt服务器,并且订阅主题,写好回调方法,大功告成