最近在写开发一个智能硬件设备,设备端写andriod应用需要用到mqtt和云平台通讯,andriod版本为11,开发工具是andriod studio,于是参考网上大侠的资源,写了一个工具类,在开发过程中遇到几个小问题,发出来供大家参考。
1、报错:cannot start service org.eclipse.paho.android.service.MqttService
解决方法:
在AndroidManifest文件中添加如下内容
<service android:name="org.eclipse.paho.android.service.MqttService"> </service>
2、报错:java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v4/content/LocalBroadcastManager
解决方法:
在gradle.properties文件中添加:
android.enableJetifier=true
mqtt工具类完整代码如下,基本可直接使用
需要在build.gradle文件中添加引用 implementation("org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0") implementation("org.eclipse.paho:org.eclipse.paho.android.service:1.1.1")
/** * mqtt * 服务 */ import android.content.Context; import android.util.Log; import org.eclipse.paho.android.service.MqttAndroidClient; import org.eclipse.paho.client.mqttv3.*; /** * mqtt工具类 * */ public class MyMqtt{ public static MqttAndroidClient mqttAndroidClient; private static MqttConnectOptions mMqttConnectOptions; private static String serverURI; public static final String PORT = "1883"; public String USERNAME = "devices_100";//用户名 public String PASSWORD = "1234";//密码 public final static String TAG = "aaa"; public static final String PUBLISH_TOPIC = "";//发布主题 public static final String SUBSCRIBE_TOPIC = "";//订阅主题 public String CLIENTID = "";//设备唯一标识 private static Context context; public MyMqtt(Context context){ this.context = context; serverURI = "tcp://192.168.0.100:1883"; CLIENTID = "11"; } /** * 初始化 */ public void init() { Log.d("mqtt", "==初始化MQ:" + serverURI); if (mqttAndroidClient == null) { try { mqttAndroidClient = new MqttAndroidClient(context, serverURI, CLIENTID); mqttAndroidClient.setCallback(mqttCallback); //设置监听订阅消息的回调 }catch (Exception e){ e.printStackTrace(); } } if (mMqttConnectOptions == null) { mMqttConnectOptions = new MqttConnectOptions(); try { mMqttConnectOptions.setCleanSession(true); //设置是否清除缓存 mMqttConnectOptions.setConnectionTimeout(10); //设置超时时间,单位:秒 mMqttConnectOptions.setKeepAliveInterval(20); //设置心跳包发送间隔,单位:秒 mMqttConnectOptions.setUserName(USERNAME); //设置用户名 mMqttConnectOptions.setPassword(PASSWORD.toCharArray()); //设置密码 } catch (Exception e) { e.printStackTrace(); } } // last will message boolean doConnect = true; String message = "{\"status\":\"" + CLIENTID + "\"}"; String topic = PUBLISH_TOPIC; Integer qos = 1; Boolean retained = true; if ((!message.equals("")) || (!topic.equals(""))) { // 最后的遗嘱 try { mMqttConnectOptions.setWill(topic, message.getBytes(), qos.intValue(), retained.booleanValue()); } catch (Exception e) { Log.d("mqtt", "==Exception Occured=="); doConnect = false; iMqttActionListener.onFailure(null, e); } } if (doConnect) { doClientConnection(); } } /** * 连接MQTT服务器 */ private static void doClientConnection() { try { if (!mqttAndroidClient.isConnected()) { Log.d("mqtt", "====连接MQTT服务器===" + serverURI); mqttAndroidClient.connect(mMqttConnectOptions, context, iMqttActionListener); } } catch (Exception e) { e.printStackTrace(); } } /** * 发布 * * @param message 消息 */ public static void publish(String message) { String topic = PUBLISH_TOPIC; Integer qos = 1; Boolean retained = false; try { //参数分别为:主题、消息的字节数组、服务质量、是否在服务器保留断开连接后的最后一条消息 mqttAndroidClient.publish(topic, message.getBytes(), qos.intValue(), retained.booleanValue()); } catch (MqttException e) { e.printStackTrace(); } } /** * 响应 (收到其他客户端的消息后,响应给对方告知消息已到达或者消息有问题等) * * @param message 消息 */ public static void response(String message) { String topic = SUBSCRIBE_TOPIC; Integer qos = 1; Boolean retained = false; try { //参数分别为:主题、消息的字节数组、服务质量、是否在服务器保留断开连接后的最后一条消息 mqttAndroidClient.publish(topic, message.getBytes(), qos.intValue(), retained.booleanValue()); } catch (MqttException e) { e.printStackTrace(); } } //MQTT是否连接成功的监听 private static IMqttActionListener iMqttActionListener = new IMqttActionListener() { @Override public void onSuccess(IMqttToken arg0) { Log.d("mqtt", "==mqtt连接成功 " + serverURI); try { if (mqttAndroidClient != null) { mqttAndroidClient.subscribe(PUBLISH_TOPIC + GlobalVariables.device.deviceId, 1);//订阅主题,参数:主题、服务质量 } } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(IMqttToken arg0, Throwable arg1) { arg1.printStackTrace(); Log.d("mqtt", "==mqtt连接失败 ==" + arg1); doClientConnection();//连接失败,重连(可关闭服务器进行模拟) } }; //订阅主题的回调 private MqttCallback mqttCallback = new MqttCallback() { @Override public void messageArrived(String topic, MqttMessage msgStr) throws Exception { try { String enCodeMsg = new String(msgStr.getPayload()); Log.d("mqtt", "==收到消息: " + enCodeMsg); //收到其他客户端的消息后,响应给对方告知消息已到达或者消息有问题等 //response("message arrived"); } catch (Exception e) { e.printStackTrace(); } } @Override public void deliveryComplete(IMqttDeliveryToken arg0) { } @Override public void connectionLost(Throwable arg0) { Log.d("mqtt", "==连接断开 "); doClientConnection();//连接断开,重连 } }; public static void disconnect(Context context) { try { if (mqttAndroidClient != null && mqttAndroidClient.isConnected()) { mqttAndroidClient.unsubscribe(PUBLISH_TOPIC); mqttAndroidClient.unregisterResources(); mqttAndroidClient.disconnect(0); //断开连接 mqttAndroidClient = null; } } catch (Exception e) { e.printStackTrace(); } } }