Android连接阿里云(四)
1.首先建立一个空的新工程
2.导入MQTT相关的包

3.在AndroidMainfest.xml文件里添加语句
<!-- 访问网络,网络定位需要上网 -->
<uses-permission android:name="android.permission.INTERNET"
/>
只有添加这句话,Android才能访问网络。

添加xml界面,如下图所示。
连接等7个绿色的是Button,光照强度和温度右边都有一个空白的TextView。

添加两个MQTT类

MqttCallbackBus的代码
1 public class MqttCallbackBus implements MqttCallback { 2 3 @Override 4 public void connectionLost(Throwable cause) { 5 Logger.e(cause.getMessage()); 6 } 7 8 @Override 9 public void messageArrived(String topic, MqttMessage message) { 10 Logger.d(topic + "====" + message.toString()); 11 String msg=message.toString().trim(); 12 EventBus.getDefault().post(msg); 13 } 14 15 @Override 16 public void deliveryComplete(IMqttDeliveryToken token) { 17 } 18 19 }
MqttManager 的代码
1 public class MqttManager { 2 // 单例 3 private static MqttManager mInstance = null; 4 // 回调 5 private MqttCallback mCallback; 6 7 // Private instance variables 8 private MqttClient client; 9 private MqttConnectOptions conOpt; 10 private boolean clean = true; 11 12 private MqttManager() { 13 mCallback = new MqttCallbackBus(); 14 } 15 16 public static MqttManager getInstance() { 17 if (null == mInstance) { 18 mInstance = new MqttManager(); 19 } 20 return mInstance; 21 } 22 23 /** 24 * 释放单例, 及其所引用的资源 25 */ 26 public static void release() { 27 try { 28 if (mInstance != null) { 29 mInstance.disConnect(); 30 mInstance = null; 31 } 32 } catch (Exception e) { 33 34 } 35 } 36 37 /** 38 * 创建Mqtt 连接 39 * 40 * @param brokerUrl Mqtt服务器地址(tcp://xxxx:1863) 41 * @param userName 用户名 42 * @param password 密码 43 * @param clientId clientId 44 * @return 45 */ 46 public boolean creatConnect(String brokerUrl, String userName, String password, String clientId) { 47 boolean flag = false; 48 String tmpDir = System.getProperty("java.io.tmpdir"); 49 MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir); 50 51 try { 52 // Construct the connection options object that contains connection parameters 53 // such as cleanSession and LWT 54 conOpt = new MqttConnectOptions(); 55 conOpt.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1); 56 conOpt.setCleanSession(clean); 57 if (password != null) { 58 conOpt.setPassword(password.toCharArray()); 59 } 60 if (userName != null) { 61 conOpt.setUserName(userName); 62 } 63 64 // Construct an MQTT blocking mode client 65 client = new MqttClient(brokerUrl, clientId, dataStore); 66 67 // Set this wrapper as the callback handler 68 client.setCallback(mCallback); 69 flag = doConnect(); 70 } catch (MqttException e) { 71 Logger.e(e.getMessage()); 72 } 73 74 return flag; 75 } 76 77 /** 78 * 建立连接 79 * 80 * @return 81 */ 82 public boolean doConnect() { 83 boolean flag = false; 84 if (client != null) { 85 try { 86 client.connect(conOpt); 87 Logger.d("Connected to " + client.getServerURI() + " with client ID " + client.getClientId()); 88 flag = true; 89 } catch (Exception e) { 90 } 91 } 92 return flag; 93 } 94 95 /** 96 * Publish / send a message to an MQTT server 97 * 98 * @param topicName the name of the topic to publish to 99 * @param qos the quality of service to delivery the message at (0,1,2) 100 * @param payload the set of bytes to send to the MQTT server 101 * @return boolean 102 */ 103 public boolean publish(String topicName, int qos, byte[] payload) { 104 105 boolean flag = false; 106 107 if (client != null && client.isConnected()) { 108 109 Logger.d("Publishing to topic \"" + topicName + "\" qos " + qos); 110 111 // Create and configure a message 112 MqttMessage message = new MqttMessage(payload); 113 message.setQos(qos); 114 115 // Send the message to the server, control is not returned until 116 // it has been delivered to the server meeting the specified 117 // quality of service. 118 try { 119 client.publish(topicName, message); 120 flag = true; 121 } catch (MqttException e) { 122 123 } 124 125 } 126 127 return flag; 128 } 129 130 /** 131 * Subscribe to a topic on an MQTT server 132 * Once subscribed this method waits for the messages to arrive from the server 133 * that match the subscription. It continues listening for messages until the enter key is 134 * pressed. 135 * 136 * @param topicName to subscribe to (can be wild carded) 137 * @param qos the maximum quality of service to receive messages at for this subscription 138 * @return boolean 139 */ 140 public boolean subscribe(String topicName, int qos) { 141 142 boolean flag = false; 143 144 if (client != null && client.isConnected()) { 145 // Subscribe to the requested topic 146 // The QoS specified is the maximum level that messages will be sent to the client at. 147 // For instance if QoS 1 is specified, any messages originally published at QoS 2 will 148 // be downgraded to 1 when delivering to the client but messages published at 1 and 0 149 // will be received at the same level they were published at. 150 Logger.d("Subscribing to topic \"" + topicName + "\" qos " + qos); 151 try { 152 client.subscribe(topicName, qos); 153 flag = true; 154 } catch (MqttException e) { 155 156 } 157 } 158 159 return flag; 160 161 } 162 163 /** 164 * 取消连接 165 * 166 * @throws MqttException 167 */ 168 public void disConnect() throws MqttException { 169 if (client != null && client.isConnected()) { 170 client.disconnect(); 171 } 172 } 173 }
MainActivity 的代码,根据自己定义的id更改相关代码。
1 public class MainActivity extends AppCompatActivity { 2 public static final String URL = "tcp://a1s8M2W04Q6.iot-as-mqtt.cn-shanghai.aliyuncs.com:1883";//更改为自己创建产品的三元素 3 private String userName = "phone&a1s8M24Q6";//更改为自己创建产品的三元素 4 private String password = "33fde1d18801d6020042ff4dda9d2952a74";//更改为自己创建产品的三元素 5 private String clientId = "android|securemde=3,signethod=hmacha1,timestamp=789|";//更改为自己创建产品的三元素 6 JSONObject cmdon=new JSONObject(); 7 JSONObject cmdoff=new JSONObject(); 8 JSONObject paramson=new JSONObject(); 9 JSONObject paramsoff=new JSONObject(); 10 JSONObject cmdon1=new JSONObject(); 11 JSONObject cmdoff1=new JSONObject(); 12 JSONObject paramson1=new JSONObject(); 13 JSONObject paramsoff1=new JSONObject(); 14 TextView txtWenDu1; 15 TextView txtLisence1; 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_main); 20 21 EventBus.getDefault().register(this); 22 txtWenDu1=(TextView) findViewById(R.id.txt_Temp); 23 txtLisence1= (TextView) findViewById(R.id.txt_Lisence); 24 //连接阿里云 25 findViewById(R.id.btn_Connect).setOnClickListener(new View.OnClickListener() { 26 @Override 27 public void onClick(View v) { 28 new Thread(new Runnable() { 29 @Override 30 public void run() { 31 boolean b = MqttManager.getInstance().creatConnect(URL, userName, password, clientId); 32 Logger.d("isConnected: " + b); 33 } 34 }).start(); 35 } 36 }); 37 //断开连接阿里云 38 findViewById(R.id.btn_disConnect).setOnClickListener(new View.OnClickListener() { 39 @Override 40 public void onClick(View v) { 41 new Thread(new Runnable() { 42 @Override 43 public void run() { 44 try { 45 MqttManager.getInstance().disConnect(); 46 } catch (MqttException e) { 47 48 } 49 } 50 }).start(); 51 } 52 }); 53 //获取数据 54 findViewById(R.id.btn_getData).setOnClickListener(new View.OnClickListener() { 55 @Override 56 public void onClick(View v) { 57 new Thread(new Runnable() { 58 @Override 59 public void run() { 60 MqttManager.getInstance().subscribe("/a1s8M2W04Q6/phone/user/ws", 0); 61 } 62 }).start(); 63 } 64 }); 65 //开灯 66 findViewById(R.id.btn_OnLight).setOnClickListener(new View.OnClickListener() { 67 @Override 68 public void onClick(View v) { 69 new Thread(new Runnable() { 70 @Override 71 public void run() { 72 //"{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":{\"feng\":%s}}" 73 paramson.put("light",1); 74 cmdon.put("id","123"); 75 cmdon.put("version","1.0"); 76 cmdon.put("method","thing.event.property.post"); 77 cmdon.put("params",paramson); 78 MqttManager.getInstance().publish("/sys/a1s8M2W04Q6/phone/thing/event/property/post", 0, cmdon.toJSONString().getBytes()); 79 } 80 }).start(); 81 } 82 }); 83 //光灯 84 findViewById(R.id.btn_OffLight).setOnClickListener(new View.OnClickListener() { 85 @Override 86 public void onClick(View v) { 87 new Thread(new Runnable() { 88 @Override 89 public void run() { 90 paramsoff.put("light",0); 91 cmdoff.put("id","123"); 92 cmdoff.put("version","1.0"); 93 cmdoff.put("method","thing.event.property.post"); 94 cmdoff.put("params",paramsoff); 95 MqttManager.getInstance().publish("/sys/a1s8M2W04Q6/phone/thing/event/property/post", 0, cmdoff.toJSONString().getBytes()); 96 } 97 }).start(); 98 } 99 }); 100 //开风扇 101 findViewById(R.id.btn_OnFeng).setOnClickListener(new View.OnClickListener() { 102 @Override 103 public void onClick(View v) { 104 new Thread(new Runnable() { 105 @Override 106 public void run() { 107 108 //"{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":{\"feng\":%s}}" 109 paramson1.put("feng",1); 110 cmdon1.put("id","123"); 111 cmdon1.put("version","1.0"); 112 cmdon1.put("method","thing.event.property.post"); 113 cmdon1.put("params",paramson1); 114 MqttManager.getInstance().publish("/sys/a1s8M2W04Q6/phone/thing/event/property/post", 0, cmdon1.toJSONString().getBytes()); 115 } 116 }).start(); 117 } 118 }); 119 //关风扇 120 findViewById(R.id.btn_OffFeng).setOnClickListener(new View.OnClickListener() { 121 @Override 122 public void onClick(View v) { 123 new Thread(new Runnable() { 124 @Override 125 public void run() { 126 paramsoff1.put("feng",0); 127 cmdoff1.put("id","123"); 128 cmdoff1.put("version","1.0"); 129 cmdoff1.put("method","thing.event.property.post"); 130 cmdoff1.put("params",paramsoff1); 131 MqttManager.getInstance().publish("/sys/a1s8M2W04Q6/phone/thing/event/property/post", 0, cmdoff1.toJSONString().getBytes()); 132 } 133 }).start(); 134 } 135 }); 136 } 137 /** 138 * 订阅接收到的消息 139 * 这里的Event类型可以根据需要自定义, 这里只做基础的演示 140 * 141 */ 142 @Subscribe(threadMode = ThreadMode.MAIN) 143 public void showdata ( String event){ 144 JSONObject meg= JSON.parseObject(event); 145 JSONObject meg2= JSON.parseObject(meg.get("items").toString()); 146 JSONObject Wendu= JSON.parseObject(meg2.get("CurrentTemperature").toString()); 147 JSONObject Lisence= JSON.parseObject(meg2.get("Lisence").toString()); 148 txtLisence1.setText(Lisence.get("value").toString()); 149 txtWenDu1.setText(Wendu.get("value").toString()); 150 }; 151 @Override 152 protected void onStart() { 153 super.onStart(); 154 155 } 156 157 @Override 158 protected void onResume() { 159 super.onResume(); 160 161 } 162 163 @Override 164 protected void onPause() { 165 super.onPause(); 166 167 } 168 169 @Override 170 protected void onDestroy() { 171 super.onDestroy(); 172 EventBus.getDefault().unregister(this); 173 } 174 }
运行结果
首先点击“连接”按钮,连接阿里云MQTT服务器
点击“获取数据”按钮,获取温度、光照强度(数据发送可以用MQTT.fx模拟)

下面点解开灯关灯等等按钮,都可以在阿里云上面做出相应的响应。

浙公网安备 33010602011771号