首页 > 其他分享 >Android studio制作的mqtt协议通讯app,可用于搭建的meqx服务器,不可连接阿里云

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

时间:2024-03-31 21:32:27浏览次数:23  
标签:String void private public mqtt studio new import app

首先,在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

标签:String,void,private,public,mqtt,studio,new,import,app
From: https://blog.csdn.net/weixin_61770184/article/details/137209413

相关文章

  • uni-app项目如何运行至安卓模拟器(MuMu模拟器12)
    uni-app项目如何运行至安卓模拟器(MuMu模拟器12)一篇搞定全过程,可根据个人需求通过目录进行跳转。uni-app项目也可以运行在AndroidStudio中,可根据个人需求进行选择使用。文章目录uni-app项目如何运行至安卓模拟器(MuMu模拟器12)一、本文使用工具与插件二、安装MuMu......
  • 强烈推荐:2024 年12款 Visual Studio 亲测、好用、优秀的工具,AI插件等
    工具类扩展1.ILSpy2022(免费)ILSpy是ILSpy开源反编译器的VisualStudio扩展。是一款开源、免费的、且适用于.NET平台反编译【C#语言编写的程序和库(.dll)内容】工具;可以集成在VisualStudio开发工具中,能够十分快捷方便的查看源代码内容。其中包括:1.项目案例2.NuGet......
  • Windows安装DevEco Studio
    1.在https://developer.harmonyos.com网站上注册账号;2.下载DevEcoStudio安装文件,选择Windows64位版本;3.运行安装文件,开始安装;4.选择Donotimportsettings;5.运行DevEcoStudio,安装Node.js和Ohpm;6.下载SDK; 7.创建一个鸿蒙项目,等待下载Gradle;8.......
  • FL Studio20.0中文汉化包补丁器下载2024最新版本
    FLStudio官方中文版已经上线,FLStudio20.8版本起开始支持简体中文,但推荐使用windows10系统安装,Windows7系统设置FLStudio语言为中文时若出现乱码,可以将Win10系统中的“微软雅黑”字体复制并安装进Win7系统电脑中!FLStudio20.8.2版本更新后支持Rosetta2,在Rosetta的支持......
  • FL Studio21.2.3官方中文汉化版无需破解激活
    FLStudio21.2中文版的适用人群非常广泛,主要包括以下几类:FLStudio21Win-安装包下载如下:https://wm.makeding.com/iclk/?zoneid=55981FLStudio21Mac-安装包下载如下:https://wm.makeding.com/iclk/?zoneid=55982音乐制作人:无论是专业的音乐制作人,还是音乐创作爱好者......
  • 32-3 APP渗透核心 - APP数据包抓取
    环境准备安装模拟器:在PC上安装一个Android模拟器,例如Genymotion、Bluestacks或者AndroidStudio提供的模拟器等。模拟器可以模拟手机环境,让你在PC上运行Android应用程序。下载APP:在模拟器中下载需要进行渗透测试的APP。你可以通过GooglePlay商店、APK文件或者其他渠道获......
  • Fiddler系列课程笔记(三): HTTPS及安卓&iOS设备APP抓包
    Fiddler系列课程笔记(三):HTTPS及安卓&iOS设备APP抓包1.HTTPS抓包1.1什么是HTTPS?HTTPS(全称:HyperTextTransferProtocoloverSecureSocketLayer),HTTPS协议是由HTTP加上TLS/SSL协议构建的可进行加密传输、身份认证的网络协议,主要通过数字证书、加密算法、非对称密钥等技......
  • 服务端工程师进化史-从零开始的APP开发(5)
    前章1.开发环境搭建2.项目环境搭建3.golang项目基础框架-前篇4.golang项目基础框架-后篇开始本篇开始搭建管理后台的前端项目,其实纯讲前端好像没啥营养,刚好本项目是采用旧项目改造的基础框架搭建的,就讲讲改造过程中,遇到难点,以及如何处理!主要是笔者工作期间的产物,在给......
  • 【全开源】V8黑色陪玩高端小程序源码陪练APP源码H5公众号源码电竞系统比心源码_博纳软
    陪玩高端小程序源码陪练APP源码H5公众号源码电竞系统比心源码——打造专业电竞陪玩平台的首选在电竞行业蓬勃发展的今天,陪玩服务逐渐成为了电竞爱好者们的新宠。为了满足市场需求,我们推出了陪玩高端小程序源码、陪练APP源码、H5公众号源码以及电竞系统比心源码,为您打造专业电......
  • 【全开源】V8黑色陪玩高端小程序源码陪练APP源码H5公众号源码电竞系统比心源码_博纳软
    陪玩高端小程序源码陪练APP源码H5公众号源码电竞系统比心源码——打造专业电竞陪玩平台的首选在电竞行业蓬勃发展的今天,陪玩服务逐渐成为了电竞爱好者们的新宠。为了满足市场需求,我们推出了陪玩高端小程序源码、陪练APP源码、H5公众号源码以及电竞系统比心源码,为您打造专业电......