任务:从Android设备向MQTT服务器发送“ Hello world”。
库文件:PahoMqtt 3.1.1
IDE:Android Studio 3.5
清单权限:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
Android的代码:
private String topic = "Lesson_MQTT_server";
private String broker = "tcp://[host]:[port];
private char [] pass = "the_password".toCharArray(); // Fake pass
private String user = "the_user";
private String userId = "the_user_id";
private String content = "Hello world from android device!";
private int qos = 2;
private MqttMessage message;
private MqttConnectOptions options;
private MqttClient client;
private TextView info;
private Button clickButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView)findViewById(R.id.HelloWorld);
clickButton = (Button)findViewById(R.id.MyButton);
clickButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
message = new MqttMessage();
message.clearPayload();
message.setPayload(content.getBytes());
message.setQos(qos);
message.setRetained(true);
options = new MqttConnectOptions();
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
options.setAutomaticReconnect(false);
options.setCleanSession(false);
options.setUserName(userId);
options.setPassword(pass);
client = new MqttClient (broker, user);
client.connect(options);
client.publish(topic, message);
client.disconnect(10);
client.close();
info.setText("Check your server:)");
} catch (MqttException ex){
info.setText("Ops! Something went wrong :)");
}
}
});
问题:引起MqttException。
我的观察:如果我使用eclipse IDE,则此代码可以正常工作。
MqttExceptions:原因:空,原因码:0,消息: MqttException。