MQTT协议的新手。我的代码在eclipse平台上运行良好。现在,尝试为android编写发布者mqtt客户端,订阅者正在eclipse上运行。应用程序在发布后即将关闭。请帮我完成以下代码。
public class MainActivity extends AppCompatActivity
{
String text="HELOOO";
TextView textReply;
private MqttClient client;
public static final String TOPIC = "data";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
client = new MqttClient("http://IP-address:1883", MqttClient.generateClientId());
} catch (MqttException e) {
e.printStackTrace();
System.exit(1);
}
try {
client.connect();
MqttMessage mssg=new MqttMessage();
mssg.setPayload(text.getBytes());
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
System.exit(1);
}
}
}
@arjun建议后的更改
public class MainActivity extends AppCompatActivity {
String text="HELOOO";
TextView textReply;
private MqttClient client;
public static final String TOPIC = "iot_data";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Publisher myClientTask = new Publisher();
myClientTask.execute();
}
}
class Publisher extends AsyncTask<Void, Void, Void>{
String text="helloo";
@Override
protected Void doInBackground(Void... voids) {
try {
MqttClient client = new MqttClient("tcp://Ip:1883", MqttClient.generateClientId());
client.connect();
MqttMessage mssg=new MqttMessage();
mssg.setPayload(text.getBytes());
client.publish("iot_data",mssg);
client.disconnect();
}catch(Exception e)
{
}
return null;
}
}
答案 0 :(得分:0)
也许它与您没有在客户端上正确指定ip地址有关,导致您执行system.exit(1)的异常;