给我写个安卓mqtt的代码
时间: 2024-01-02 15:03:37 浏览: 72
好的,以下是一个简单的安卓MQTT客户端的示例代码:
首先,你需要在你的安卓项目中添加以下依赖:
```
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.2'
```
接下来,你可以在你的Activity或Fragment中创建一个MQTT客户端并连接到服务器。以下是一个简单的示例:
```java
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
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.persist.MemoryPersistence;
public class MainActivity extends AppCompatActivity {
private static final String BROKER_URI = "tcp://localhost:1883";
private static final String CLIENT_ID = "android-mqtt-client";
private static final String TOPIC = "test/topic";
private MqttAsyncClient mqttClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectMqtt();
}
private void connectMqtt() {
try {
mqttClient = new MqttAsyncClient(BROKER_URI, CLIENT_ID, new MemoryPersistence());
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
mqttClient.connect(options, null, new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
// 连接丢失时的回调
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
// 收到消息时的回调
String payload = new String(message.getPayload());
Log.d("MQTT", "Received message: " + payload);
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// 消息发送完成时的回调
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
private void subscribeToTopic() {
try {
mqttClient.subscribe(TOPIC, 0);
} catch (MqttException e) {
e.printStackTrace();
}
}
private void publishMessage(String message) {
try {
mqttClient.publish(TOPIC, new MqttMessage(message.getBytes()));
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
mqttClient.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
```
以上代码中,我们创建了一个`MqttAsyncClient`实例并连接到了一个MQTT服务器。我们还实现了`MqttCallback`接口,以便在连接丢失、收到消息或消息发送完成时接收回调。
要订阅主题,我们可以调用`mqttClient.subscribe()`方法,并指定要订阅的主题和QoS级别。
要发布消息,我们可以调用`mqttClient.publish()`方法,并指定要发布的主题和消息内容。
最后,在Activity或Fragment销毁时,我们需要断开与MQTT服务器的连接。
以上代码仅为示例,实际使用时需要根据需要进行修改和调整。
阅读全文