Android studio学习笔记【结合硬件做一些简单通信(够用刚刚好)】
MQTT.jar包的使用
0.首先要在Androidmanifest.xml 允许打开网络
<!-- 允许程序打开网络套接字 --><uses-permission android:name=\"android.permission.INTERNET\" /><!-- 允许程序获取网络状态 --><uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />
1.导入jar包
2.检查是否真的导入?
3.在Mainactivity中import mqtt.jar中相关class
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 org.json.JSONException;import org.json.JSONObject;
4.在public class MainActivity最前面 定义MQTT相关成员变量
public class MainActivity extends AppCompatActivity{//定义成员private Button bt1;// 定义成员 Button 对象private ImageView im1;private TextView t1;//MQTT相关定义private String host = \"tcp://106.13.150.28:1883\";private String userName = \"android\";private String passWord = \"android\";private String mqtt_id = \"1753993264\"; //定义成自己的QQ号 切记!不然会掉线!!!private String mqtt_sub_topic = \"1753993264\"; //为了保证你不受到别人的消息 哈哈private String mqtt_pub_topic = \"1753993264_pc\"; //为了保证你不受到别人的消息 哈哈 自己QQ好后面加 _PCprivate ScheduledExecutorService scheduler;private MqttClient client;private MqttConnectOptions options;private Handler handler;
5.在onCreate里 判断msg 发送接受(最先执行的部分)
@SuppressLint(\"HandlerLeak\")@Overrideprotected void onCreate(Bundle savedInstanceState){//最先执行地方super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//设置ui//把成员与ui关联起来bt1=findViewById(R.id.bt1);//寻找真正的xml ui中的id 并且关联起来im1=findViewById(R.id.im1);//寻找真正的xml ui中的id 并且关联起来t1=findViewById(R.id.t1);//寻找真正的xml ui中的id 并且关联起来//定义按钮单击事件函数bt1.setOnClickListener(new View.OnClickListener() //单机事件函数{@Override //自动生成public void onClick(View view) //自动生成{System.out.println(\"加油\");//Toast弹窗 :在MainActivity.this 界面 弹出\"加油\" 长时间Toast.makeText(MainActivity.this,\"加油\",Toast.LENGTH_LONG).show();}});//定义图片单击事件函数im1.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View view){//Toast弹窗 :在MainActivity.this 界面 弹出\"加油\" 长时间Toast.makeText(MainActivity.this,\"我是第一個圖\",Toast.LENGTH_LONG).show();t1.setText(\"單機圖圖片完成\");//mqtt通信publishmessageplus(mqtt_pub_topic,\"open_led\");}});//*************************************************************************////初始化mqtt 连接mqttMqtt_init();startReconnect();handler = new Handler() {@SuppressLint(\"SetTextI18n\")public void handleMessage(Message msg){super.handleMessage(msg);switch (msg.what){case 1: //开机校验更新回传break;case 2: // 反馈回传break;case 3: //MQTT 收到消息回传 UTF8Buffer msg=newUTF8Buffer(object.toString());Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();t1.setText(msg.obj.toString());break;case 30: //连接失败Toast.makeText(MainActivity.this,\"连接失败\" ,Toast.LENGTH_SHORT).show();break;case 31: //连接成功Toast.makeText(MainActivity.this,\"连接成功\" ,Toast.LENGTH_SHORT).show();try {client.subscribe(mqtt_sub_topic,1);}catch (MqttException e) { e.printStackTrace();}break;default:break;}}};}
6.自定义一个发布消息的函数{更方便}
private void publishmessageplus(String topic,String message2){if (client == null || !client.isConnected()) {return;}MqttMessage message = new MqttMessage();message.setPayload(message2.getBytes());try {client.publish(topic,message);} catch (MqttException e) {e.printStackTrace();}}
7.定义mqtt先关函数
private void Mqtt_init(){try {//host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存client = new MqttClient(host, mqtt_id,new MemoryPersistence());//MQTT的连接设置options = new MqttConnectOptions();//设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接options.setCleanSession(false);//设置连接的用户名options.setUserName(userName);//设置连接的密码options.setPassword(passWord.toCharArray());// 设置超时时间 单位为秒options.setConnectionTimeout(10);// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制options.setKeepAliveInterval(20);//设置回调client.setCallback(new MqttCallback() {@Overridepublic void connectionLost(Throwable cause) {//连接丢失后,一般在这里面进行重连System.out.println(\"connectionLost----------\");//startReconnect();}@Overridepublic void deliveryComplete(IMqttDeliveryToken token) {//publish后会执行到这里System.out.println(\"deliveryComplete---------\"+ token.isComplete());}@Overridepublic void messageArrived(String topicName, MqttMessage message)throws Exception {//subscribe后得到的消息会执行到这里面System.out.println(\"messageArrived----------\");Message msg = new Message();msg.what = 3; //收到消息标志位msg.obj = topicName + \"---\" + message.toString();handler.sendMessage(msg); // hander 回传}});} catch (Exception e) {e.printStackTrace();}}private void Mqtt_connect() {new Thread(new Runnable() {@Overridepublic void run() {try {if(!(client.isConnected()) ) //如果还未连接{client.connect(options);Message msg = new Message();msg.what = 31;handler.sendMessage(msg);}} catch (Exception e) {e.printStackTrace();Message msg = new Message();msg.what = 30;handler.sendMessage(msg);}}}).start();}private void startReconnect() {scheduler = Executors.newSingleThreadScheduledExecutor();scheduler.scheduleAtFixedRate(new Runnable() {@Overridepublic void run() {if (!client.isConnected()) {Mqtt_connect();}}}, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);}
测试部分
注:这是一篇 学习B站up: 阿正啷个哩个啷 的学习笔记。阿正哥牛逼~~!!