这是一个基本问题 - NPE又名NullPointerException :-)
你正打算打电话 mqttAndroidClient.publish(publishTopic, message) 但是 mqttAndroidClient 尚未初始化(由您,在您的 setupMqtt 方法)因此无效。
mqttAndroidClient.publish(publishTopic, message)
mqttAndroidClient
setupMqtt
你可以添加一个 if (mqttAndroidClient != null) 条件或只是捕捉并忽略NPE:
if (mqttAndroidClient != null)
public void publishMessage(String text) { try { MqttMessage message = new MqttMessage(); message.setPayload(text.getBytes()); mqttAndroidClient.publish(publishTopic, message); Log.d(logTag, "Message published"); } catch (NullPointerException | MqttException ex) { ex.printStackTrace(); } }