Android studio制作的mqtt协议通讯app,可用于搭建的meqx服务器,不可连接阿里云

首先,在app目录下创建一个libs文件夹,导入相应的MQTT的jar包,然后右击jar包拉到最后找到Add...的一个选项,单击就OK了

然后就是添加一些权限

添加另一个layout的名字

activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <!--添加id就修改layout_gravity、layout_margin布局-->
    
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/back">


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="200dp"
        android:orientation="horizontal">

    <TextView
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:text="服务器IP:"
        android:textColor="@color/white"
        android:textSize="28sp"/>

        <EditText
            android:id="@+id/Host"
            android:layout_width="280dp"
            android:layout_height="wrap_content"
            android:textColor="@color/white"
            android:textSize="18sp"/>
    </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="260dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:text="用  户 名:"
                android:textColor="@color/white"
                android:textSize="28sp"/>

            <EditText
                android:id="@+id/UserName"
                android:layout_width="230dp"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textSize="28sp"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="320dp"
            android:orientation="horizontal">

        <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:text="密       码:"
            android:textColor="@color/white"
            android:textSize="28sp"/>

        <EditText
            android:id="@+id/PassWord"
            android:layout_width="230dp"
            android:layout_height="wrap_content"
            android:password="true"
            android:textColor="@color/white"
            android:textSize="28sp"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="420dp"
            android:gravity="center"
            android:orientation="horizontal">


            <Button
                android:id="@+id/login"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="登陆"
                android:textAllCaps="true"
                android:textColor="#EE4000"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
                android:textSize="28sp" />

        </LinearLayout>

    </RelativeLayout>
</LinearLayout>

funtion.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/back9">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="20dp"
            android:gravity="left">


            <TextView
                android:layout_width="80dp"
                android:layout_height="wrap_content"
                android:text="温度:"
                android:textSize="27sp"
                android:textColor="@color/black"/>

            <TextView
                android:id="@+id/temp"
                android:layout_width="80dp"
                android:layout_height="wrap_content"
                android:text="0"
                android:textSize="28sp"
                android:textColor="#EE4000"/>

            <TextView
                android:layout_width="60dp"
                android:layout_height="wrap_content"
                android:text="℃"
                android:textSize="28sp"
                android:textColor="@color/black"/>

            <Button
                android:id="@+id/led_open"
                android:layout_width="90dp"
                android:layout_height="wrap_content"
                android:text="开灯"
                android:textAllCaps="true"
                android:textSize="17sp"
                android:textColor="@color/black"/>

            <Button
                android:id="@+id/led_close"
                android:layout_width="90dp"
                android:layout_height="wrap_content"
                android:text="关灯"
                android:textAllCaps="true"
                android:textSize="17sp"
                android:textColor="@color/black"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="80dp"
            android:gravity="left">


            <TextView
                android:layout_width="80dp"
                android:layout_height="wrap_content"
                android:text="湿度:"
                android:textSize="27sp"
                android:textColor="@color/black"/>

            <TextView
                android:id="@+id/humi"
                android:layout_width="80dp"
                android:layout_height="wrap_content"
                android:text="0"
                android:textSize="27sp"
                android:textColor="#EE4000"/>

            <TextView
                android:layout_width="60dp"
                android:layout_height="wrap_content"
                android:text="%RH"
                android:textSize="27sp"
                android:textColor="@color/black"/>

            <Button
                android:id="@+id/beep_open"
                android:layout_width="90dp"
                android:layout_height="wrap_content"
                android:text="鸣开"
                android:textAllCaps="true"
                android:textSize="17sp"
                android:textColor="@color/black"/>

            <Button
                android:id="@+id/beep_close"
                android:layout_width="90dp"
                android:layout_height="wrap_content"
                android:text="鸣关"
                android:textAllCaps="true"
                android:textSize="17sp"
                android:textColor="@color/black"/>

        </LinearLayout>


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="580dp"
            android:gravity="center"
            android:orientation="horizontal">
        <Button
            android:id="@+id/go_back"
            android:layout_width="200dp"
            android:layout_height="80dp"
            android:text="返回登陆"
            android:textAllCaps="true"
            android:textColor="#EE4000"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp"
            android:textSize="28sp" />
        </LinearLayout>


    </RelativeLayout>
</LinearLayout>

mainactivity.java

package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import android.widget.Toast;

import java.util.Map;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
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;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText Host, UserName, PassWord;
    private Button login;
    private static Handler handler;
    private static MqttClient client;
    private static MqttConnectOptions options;
    private static ScheduledExecutorService scheduler;
    //private String mqtt_pub_topic="test3";//发
    private String mqtt_sub_topic="test2";//订阅


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();



        handler = new Handler() {
            @SuppressLint({"SetTextIl8n", "HandlerLeak"})
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1: //开机校验更新回传
                        break;
                    case 2: //反馈回转
                        break;
                    case 3: //MQTT收到消息回传
                        String message = msg.obj.toString();
                        String[] str;
                        int t = 0;
                        int h = 0;
                        try {
                                str = message.split(":");
                                for (int i = 0; i < str.length; i++) {
                                    if (str[i].equals("temp")) {
                                        t = i + 1;
                                    }
                                    if (str[i].equals("humi")) {
                                        h = i + 1;
                                    }
                                }
                                if(t==0){
                                    str[t]="- -";
                                }
                                if(h==0){
                                    str[h]="- -";
                                }
                                funtion.set_str(str[t], str[h]);
                        } catch(Exception e){
                        e.printStackTrace();
                    }
                        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,0);//订阅
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }
    private void initView() {
        Host = findViewById(R.id.Host);
        UserName = findViewById(R.id.UserName);
        PassWord = findViewById(R.id.PassWord);
        login = findViewById(R.id.login);
        login.setOnClickListener(this);
    }

    @Override
    public void onClick (View v) {
        if (v.getId() == R.id.login) {
                doLogin();
                startReconnect();
                Intent intent = new Intent(this, funtion.class);
                startActivity(intent);

        }
    }

    private void initData() {
        Map<String, String> map = FileSave.getUserinfo(this);
        if (map != null) {
            Host.setText(map.get("uhost"));
            UserName.setText(map.get("uname"));
            PassWord.setText(map.get("upass"));
        }
    }

    private void showMsg(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    private void doLogin() {
        String uhost = Host.getText().toString().trim();
        String uname = UserName.getText().toString().trim();
        String upass = PassWord.getText().toString().trim();

        if (uhost == null || TextUtils.isEmpty(uhost)) {
            showMsg("请填写ip地址");}
        if (uname == null || TextUtils.isEmpty(uname)) {
            showMsg("请填写用户名");
        } else if (upass == null || TextUtils.isEmpty(upass)) {
            showMsg("请填写密码");
        } else {
            //todo:存数据
            boolean flag = FileSave.saveUserInfo(this, uhost, uname, upass);
        }
        try {
            String mqtt_id=uname;
            //host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
            client= new MqttClient(uhost, mqtt_id,
                    new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            //设置连接的用户名
            options.setUserName(uname);
            //设置连接的密码
            options.setPassword(upass.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后,一般在这里面进行重连
                    System.out.println("connectionLost----------");
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }
                @Override
                public 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);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void Mqtt_connect() {
        new Thread(new Runnable() {
            @Override
            public 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 static void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    Mqtt_connect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }
    public static 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();
        }
    }

}

filsava.java   用于登陆信息保存的

package com.example.myapplication;

import android.content.Context;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class FileSave {
    private static final String filename="userdata.txt";
    public static boolean saveUserInfo(Context context,String uhost, String uname, String upass){
        FileOutputStream fos =null;
        try{
            fos =context.openFileOutput(filename,Context.MODE_PRIVATE);
            String str = String.format("%s; %s ;%s",uhost,uname,upass);
            fos.write(str.getBytes());
            return true;
        }catch (Exception ex){
            ex.printStackTrace();
            return false;
        }finally{
            try{
                if(fos!=null){
                    fos.close();
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }

    public static Map<String,String> getUserinfo(Context context){
        String content ="";
        FileInputStream fis =null;
        Map<String,String> map = null;
        try{
            fis =context.openFileInput(filename);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            content = new String(buffer);
            map= new HashMap<>();
            String[] infos = content.split(";");
            map.put("uhost",infos[0]);
            map.put("uname",infos[1]);
            map.put("upass",infos[2]);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally{
            try{
                if(fis!=null){
                    fis.close();
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
        return map;
    }

}

funtion.java        第二个界面按键和文本显示操作

package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;


public class funtion extends AppCompatActivity{
    private Button go_back,led_open,led_close,beep_open,beep_close;
    private String mqtt_pub_topic="test3";//发
    private static TextView temp;
    private static TextView humi;



    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.funtion);

        go_back=findViewById(R.id.go_back);
        led_open=findViewById(R.id.led_open);
        led_close=findViewById(R.id.led_close);
        beep_open=findViewById(R.id.beep_open);
        beep_close=findViewById(R.id.beep_close);
        temp =findViewById(R.id.temp);
        humi =findViewById(R.id.humi);

        go_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开
                finish();
            }
        });

        led_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开

                 MainActivity.publishmessageplus(mqtt_pub_topic,"0xb70");
            }

        });

        led_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开
                MainActivity.publishmessageplus(mqtt_pub_topic,"0xb71");
            }
        });

        beep_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开

                MainActivity.publishmessageplus(mqtt_pub_topic,"0xb60");
            }

        });

        beep_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开
                MainActivity.publishmessageplus(mqtt_pub_topic,"0xb61");
            }
        });
    }
    public static void set_str(String buf1,String buf2) {

        temp.setText(buf1);
        humi.setText(buf2);
    }

}
链接:https://pan.baidu.com/s/1xCJHvXOk38ESJ7Zx0KXoxA 
提取码:u91z

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值