下载Windows版的 mosquitto-1.1.2-install-win32.exe
下载android Demo包 AndroidPushNotificationsDemo-master.zip
安装mosquitto-1.1.2-install-win32.exe后 进入安装目录
双击打开mosquitto.exe
Android Studio 打开 Demo包
修改
private static final String MQTT_HOST = "192.168.0.137";
public MQTTConnection(String brokerHostName, String initTopic) throws MqttException {
// Create connection spec
String mqttConnSpec = "tcp://" + brokerHostName + "@" + MQTT_BROKER_PORT_NUM;
// Create the client and connect
mqttClient = MqttClient.createMqttClient(mqttConnSpec, MQTT_PERSISTENCE);
String clientID = MQTT_CLIENT_ID + "/" + mPrefs.getString(PREF_DEVICE_ID, "");
mqttClient.connect(clientID, MQTT_CLEAN_START, MQTT_KEEP_ALIVE);
// register this client app has being able to receive messages
mqttClient.registerSimpleHandler(this);
// Subscribe to an initial topic, which is combination of client ID and device ID.
//initTopic = MQTT_CLIENT_ID + "/" + initTopic;
initTopic = "aaa"; //自定义主题
subscribeToTopic(initTopic); //订阅主题
log("Connection established to " + brokerHostName + " on topic " + initTopic);
// Save start time
mStartTime = System.currentTimeMillis();
// Star the keep-alives
startKeepAlives();
}
编译后安装在手机上 打开APP 启动Service
在电脑上打开CMD
mosquitto_pub.exe -t aa -m "hello" -i ID 发送消息
ID为手机显示的DeviceID