该篇文章从eoeAndroid搬迁过来的,原文地址:[Android实例] MQTT消息推送,即时通讯
前几天刚学习了MQTT服务器搭建和如何使用MQTT进行消息推送,不清楚的同学可以查看[Android实例] MQTT协议,Android消息推送
MQTT不仅可以做消息推送,还能够实现即时通讯,今天没事做了个DEMO贡献个大家
主要代码:
接收消息展示:
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
try {
mqttClient = new MqttClient(Constant.MQTT_SERVERURL, Constant.CLIENT_ID,
new MemoryPersistence());
mqttClient.setCallback(new MqttCallback() {
@Override
public void messageArrived(String topicName, MqttMessage message)
throws Exception {
// TODO Auto-generated method stub
String str = new String(message.getPayload());
if (str != null && !str.equals("")) {
if (MainActivity.handler != null) {
Message msg = new Message();
msg.obj = str;
msg.what = 0;
MainActivity.handler.sendMessage(msg);
}
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// TODO Auto-generated method stub
}
@Override
public void connectionLost(Throwable cause) {
// TODO Auto-generated method stub
}
});
mqttClient.connect();
mqttClient.subscribe(Constant.CLIENT_TOPIC);
} catch (MqttException e) {
// TODO Auto-generated catch block
Log.i("Log", e.getMessage());
e.printStackTrace();
}
}
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
textView.setText(textView.getText().toString() + "\n"
+ Constant.SERVER_ID + ":" + msg.obj);
}
};
发送消息:
String msg = editText.getText().toString();
if (msg == null || msg.equals("")) {
Toast.makeText(MainActivity.this, "输入内容不能为空",
Toast.LENGTH_SHORT).show();
return;
}
try {
MqttClient client = new MqttClient(Constant.MQTT_SERVERURL,
MqttClient.generateClientId(),
new MemoryPersistence());
client.connect();
MqttTopic temperatureTopic = client
.getTopic(Constant.SERVER_TOPIC);
MqttMessage message = new MqttMessage(msg.getBytes());
temperatureTopic.publish(message);
client.disconnect();
textView.setText(textView.getText().toString() + "\n"
+ "===>本地增加---" + Constant.CLIENT_ID + ":" + msg);
editText.setText("");
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
由于是简易demo,这里有一点要注意的是,用两个模拟器测试的时候,demo里面的Constant.java类需要进行根据不同的模拟器有选择去注释
public static String MQTT_SERVERURL = “tcp://192.168.0.79:1883”;
/***************************用户二安装的时候注释掉************************************/
public static String CLIENT_ID = "用户一";
public static String CLIENT_TOPIC = "接受用户二信息";
public static String SERVER_ID = "用户二";
public static String SERVER_TOPIC = "接受用户一信息";
/***************************用户一安装的时候注释掉***********************************/
// public static String CLIENT_ID = “用户二”;
// public static String CLIENT_TOPIC = “接受用户一信息”;
//
// public static String SERVER_ID = “用户一”;
// public static String SERVER_TOPIC = “接受用户二信息”;
代码里面如果有不合理的地方敬请见谅,毕竟是个简易Demo,各位看官别太在意
下载地址:项目代码