Android mqtt入门 Android studio
2018年04月09日 14:02:30 hbw020 阅读数:1564
分享 mqtt简单使用介绍:
1、as创建工程
2、官网下载mqtt支持包放入lib文件,点击打开链接,https://repo.eclipse.org/content/repositories/paho-releases/org/eclipse/paho/org.eclipse.paho.client.mqttv3/1.2.0/。当前使用的是:
org.eclipse.paho.client.mqttv3-1.2.0.jar
3、然后开始工作:
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;import org.eclipse.paho.client.mqttv3.MqttCallback;import org.eclipse.paho.client.mqttv3.MqttClient;import org.eclipse.paho.client.mqttv3.MqttConnectOptions;import org.eclipse.paho.client.mqttv3.MqttException;import org.eclipse.paho.client.mqttv3.MqttMessage;import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;/***全局主服务分发和接收mqtt消息*/public class MQTTServiceextends Service {private static final StringTAG="MQTTService"; public final StringSERVICE_CLASSNAME ="de.eclipsemagazin.mqtt.push.MQTTService"; private Handlerhandler; // private String host = "tcp://192.168.2.151:1883";// private String userName = "admin";// private String passWord = "password"; private int i =1; private static MqttClientclient; // private String myTopic = "qaiot/user/f5c71e03-c324-4b32-823c-563471e86da9";// private String myTopic = "qaiot/user/f5c71e03-c324-4b32"; private StringmyTopic ="qaiot/server/user/1.0/cn"; StringclientId ="qaiot/user/f5c71e03-c324-4b32"; private MqttConnectOptionsoptions; private static ScheduledExecutorServicescheduler; public JooanMQTTService() { }@Override public IBinderonBind(Intent intent) {// TODO: Return the communication channel to the service.throw new UnsupportedOperationException("Not yet implemented"); }@Override public void onCreate() {super.onCreate(); initMqttClient(); handler =new Handler() {@Override public void handleMessage(Message msg) {super.handleMessage(msg); if (msg.what ==1) { Toast.makeText(JooanApplication.get(), (String) msg.obj, Toast.LENGTH_SHORT).show(); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notification =new Notification(R.drawable.menu_item_small_bg, "Mqtt即时推送", System.currentTimeMillis());// notification.contentView = new RemoteViews("com.hxht.testmqttclient", R.layout.activity_notification); notification.contentView =new RemoteViews("com.jooan.qiaoanzhilian", R.layout.service_jooan_mqtt_notification);