精华内容
下载资源
问答
  • Android MQTT

    2019-12-02 15:20:26
    1.在项目根目录下的build.gradle中添加 repositories { maven { url ... } } 2.在app目录下的build.gradle中添加: //mqtt implementation 'org.ecli...

    1.在项目根目录下的build.gradle中添加

    repositories {
        maven {
            url "https://repo.eclipse.org/content/repositories/paho-releases/"
        }
    }
    

    在这里插入图片描述
    2.在app目录下的build.gradle中添加:

     //mqtt
        implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
        implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
       //implementation 'com.android.support:support-v4:4.4.1'
    

    3.权限

        <uses-permission android:name="android.permission.WAKE_LOCK" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.READ_PHONE_STATE" />
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.INTERNET" />
    

    4.在AndroidManifest.xml中添加

        <!-- Mqtt服务 -->
        <service android:name="org.eclipse.paho.android.service.MqttService" />
    

    5.新建EasyMqttMethod.class

    public class EasyMqttMethod {
    
        private static OnConnectListener onConnectListener;
    
        /**
         * 构建EasyMqttService对象
         */
        public EasyMqttService buildEasyMqttService() {
            EasyMqttService mMQTTService = new EasyMqttService.Builder()
                    //设置自动重连
                    .autoReconnect(true)
                    //设置不清除回话session 可收到服务器之前发出的推送消息
                    .cleanSession(false)
                    //唯一标示 保证每个设备都唯一就可以 建议 imei
                    .clientId("RelayUAVGround")     //中继无人机地面端
                    //mqtt服务器地址 格式例如:tcp://10.0.261.159:1883
                    .serverUrl("tcp://212.64.56.66:1883")
                    //心跳包默认的发送间隔
                    .keepAliveInterval(20)
                    //构建出EasyMqttService 建议用application的context
                    .bulid(CompleteWidgetActivity.getContext().getApplicationContext());
            connect(mMQTTService);
            return mMQTTService;
        }
    
        /**
         * 连接Mqtt服务器
         */
        public void connect(final EasyMqttService mqttService) {
            mqttService.connect(new IEasyMqttCallBack() {
                @Override
                public void messageArrived(String topic, String message, int qos) {
                    //推送消息到达
                    //通过接口传递接收到的数据
                    getOnConnectListener().onConnectSuccess(message);
                }
    
                @Override
                public void connectionLost(Throwable arg0) {
                    //连接断开
                    Log.e("-----------", "连接断开");
    //                ConnectionStatus = "连接断开";
                }
    
                @Override
                public void deliveryComplete(IMqttDeliveryToken arg0) {
                }
    
                @Override
                public void connectSuccess(IMqttToken arg0) {
                    //连接成功
                    subscribe(mqttService);
                    Log.e("-----------", "MQTT连接成功 ");
                }
    
                @Override
                public void connectFailed(IMqttToken arg0, Throwable arg1) {
                    //连接失败
                    Log.e("-----------", "连接失败" + " " + arg1.getMessage());
                }
            });
        }
    
        /**
         * 订阅主题 这里订阅三个主题分别是"a", "b", "c"
         */
        public void subscribe(EasyMqttService mqttService) {
            Log.e("----------", "订阅主题");
    
            //主题对应的推送策略 分别是0, 1, 2 建议服务端和客户端配置的主题一致
            // 0 表示只会发送一次推送消息 收到不收到都不关心
            // 1 保证能收到消息,但不一定只收到一条
            // 2 保证收到切只能收到一条消息
            int[] qoss = new int[]{0};
            mqttService.subscribe(new String[] {"RelayUAVKey"}, qoss);
        }
    
        /**
         * 发布String消息
         */
        public void publishString(final String msg, String topic, int qos, boolean retained, EasyMqttService mqttService) {
            if(mqttService != null) {
                mqttService.publishString(msg, topic, qos, retained);
            }
        }
    
        /**
         * 发布Byte消息
         */
        public void publishByte(byte[] msg, String topic, int qos, boolean retained, EasyMqttService mqttService) {
            if(mqttService != null) {
                mqttService.publishByte(msg, topic, qos, retained);
            }
        }
    
        //创建方法
        public void getMsg(OnConnectListener listener) {
            setOnConnectListener(listener);
        }
    
        //回调接口
        public interface OnConnectListener{
            //连接成功
            void onConnectSuccess(String msg);
            //连接异常信息
            void onConnectFailed(Exception e);
        }
    
        /**
         * 判断服务是否连接
         */
        public boolean isConnected(EasyMqttService mqttService) {
            return mqttService.isConnected();
        }
    
        private OnConnectListener getOnConnectListener() {
            return onConnectListener;
        }
    
        private void setOnConnectListener(OnConnectListener onConnectListener) {
            this.onConnectListener = onConnectListener;
        }
    }
    

    5.新建EasyMqttService.class

    /**
     * Mqtt服务
     * @author GrainRain
     */
    public class EasyMqttService implements Serializable {
        private final String TAG = "EasyMqttService";
        private boolean canDoConnect = true;
    
        private MqttAndroidClient client;
        private MqttConnectOptions conOpt;
    
        private Context context;
        private String serverUrl = "";
        private String userName = "admin";
        private String passWord = "password";
        private String clientId = "";
        private int timeOut = 10;
        private int keepAliveInterval = 20;
        private boolean retained = false;
        private boolean cleanSession = true;
        private boolean autoReconnect = true;
        private IEasyMqttCallBack starMQTTCallBack;
    
        /**
         * builder设计模式
         *
         * @param builder
         */
        private EasyMqttService(Builder builder) {
            this.context = builder.context;
            this.serverUrl = builder.serverUrl;
            this.userName = builder.userName;
            this.passWord = builder.passWord;
            this.clientId = builder.clientId;
            this.timeOut = builder.timeOut;
            this.keepAliveInterval = builder.keepAliveInterval;
            this.retained = builder.retained;
            this.cleanSession = builder.cleanSession;
            this.autoReconnect = builder.autoReconnect;
    
            init();
        }
    
        /**
         * Builder 构造类
         */
        public static final class Builder {
    
            private Context context;
            private String serverUrl;
            private String userName = "admin";
            private String passWord = "password";
            private String clientId;
            private int timeOut = 10;
            private int keepAliveInterval = 20;
            private boolean retained = false;
            private boolean cleanSession = false;
            private boolean autoReconnect = false;
    
            public Builder serverUrl(String serverUrl) {
                this.serverUrl = serverUrl;
                return this;
            }
    
            public Builder userName(String userName) {
                this.userName = userName;
                return this;
            }
    
            public Builder passWord(String passWord) {
                this.passWord = passWord;
                return this;
            }
    
            public Builder clientId(String clientId) {
                this.clientId = clientId;
                return this;
            }
    
            public Builder timeOut(int timeOut) {
                this.timeOut = timeOut;
                return this;
            }
    
            public Builder keepAliveInterval(int keepAliveInterval) {
                this.keepAliveInterval = keepAliveInterval;
                return this;
            }
    
            public Builder retained(boolean retained) {
                this.retained = retained;
                return this;
            }
    
            public Builder autoReconnect(boolean autoReconnect) {
                this.autoReconnect = autoReconnect;
                return this;
            }
    
            public Builder cleanSession(boolean cleanSession) {
                this.cleanSession = cleanSession;
                return this;
            }
    
            public EasyMqttService bulid(Context context) {
                this.context = context;
                return new EasyMqttService(this);
            }
        }
    
        /**
         * 发布消息
         * @param msg
         * @param topic
         * @param qos
         * @param retained
         */
        public void publishString(String msg, String topic, int qos, boolean retained) {
            try {
                client.publish(topic, msg.getBytes(), qos, retained);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public void publishByte(byte[] msg, String topic, int qos, boolean retained) {
            try {
                client.publish(topic, msg, qos, retained);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private void init() {
            // 服务器地址(协议+地址+端口号)
            client = new MqttAndroidClient(context, serverUrl, clientId);
            // 设置MQTT监听并且接受消息
            client.setCallback(mqttCallback);
    
            conOpt = new MqttConnectOptions();
            // 清除缓存
            conOpt.setCleanSession(cleanSession);
            // 设置超时时间,单位:秒
            conOpt.setConnectionTimeout(timeOut);
            // 心跳包发送间隔,单位:秒
            conOpt.setKeepAliveInterval(keepAliveInterval);
            // 用户名
            conOpt.setUserName(userName);
            // 密码
            conOpt.setPassword(passWord.toCharArray());
            conOpt.setAutomaticReconnect(autoReconnect);
        }
    
        /**
         * 关闭客户端
         */
        public void close() {
            try {
                client.close();
            } catch (Exception e) {
                Log.e(TAG,e.toString());
            }
        }
    
        /**
         * 连接MQTT服务器
         */
        public void connect(IEasyMqttCallBack starMQTTCallBack) {
            this.starMQTTCallBack = starMQTTCallBack;
            if (canDoConnect && !client.isConnected()) {
                try {
                    client.connect(conOpt,null, iMqttActionListener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
        /**
         * 订阅主题
         *
         * @param topics 主题
         * @param qos    策略
         */
        public void subscribe(String[] topics, int[] qos) {
            try {
                // 订阅topic话题
                Log.i(TAG, "execute subscribe -- qos = " + qos.toString());
                client.subscribe(topics, qos);
            } catch (Exception e) {
                Log.e(TAG,e.toString());
            }
        }
    
        /**
         * 断开连接
         */
        public void disconnect(){
            try {
                client.disconnect();
            } catch (Exception e) {
                Log.e(TAG,e.toString());
            }
        }
    
        /**
         * 判断连接是否断开
         */
        public boolean isConnected(){
            try {
                return client.isConnected();
            } catch (Exception e) {
                Log.e(TAG,e.toString());
            }
            return false;
        }
    
        /**
         *  MQTT是否连接成功
         */
        private IMqttActionListener iMqttActionListener = new IMqttActionListener() {
    
            @Override
            public void onSuccess(IMqttToken arg0) {
                Log.i(TAG, "mqtt connect success ");
                if (starMQTTCallBack != null) {
                    starMQTTCallBack.connectSuccess(arg0);
                }
            }
    
            @Override
            public void onFailure(IMqttToken arg0, Throwable arg1) {
                Log.i(TAG, "mqtt connect failed ");
                if (starMQTTCallBack != null) {
                    starMQTTCallBack.connectFailed(arg0, arg1);
                }
            }
        };
    
        // MQTT监听并且接受消息
        private MqttCallback mqttCallback = new MqttCallback() {
    
            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
    
                String msgContent = new String(message.getPayload());
                String detailLog = topic + ";qos:" + message.getQos() + ";retained:" + message.isRetained();
                Log.i(TAG, "messageArrived:" + msgContent);
                Log.i(TAG, detailLog);
                if (starMQTTCallBack != null) {
                    starMQTTCallBack.messageArrived(topic, msgContent, message.getQos());
                }
            }
    
            @Override
            public void deliveryComplete(IMqttDeliveryToken arg0) {
                if (starMQTTCallBack != null) {
                    starMQTTCallBack.deliveryComplete(arg0);
                }
                Log.i(TAG, "deliveryComplete");
            }
    
            @Override
            public void connectionLost(Throwable arg0) {
                if (starMQTTCallBack != null) {
                    starMQTTCallBack.connectionLost(arg0);
                }
                Log.i(TAG, "connectionLost");
                // 失去连接,重连
            }
        };
    
        /**
         * 判断网络是否连接
         */
        private boolean isConnectIsNomarl() {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            @SuppressLint("MissingPermission") NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if (info != null && info.isAvailable()) {
                String name = info.getTypeName();
                Log.i(TAG, "MQTT current network name:" + name);
                return true;
            } else {
                Log.i(TAG, "MQTT no network");
                return false;
            }
        }
    }
    

    6.新建接口IEasyMqttCallBack

    public interface IEasyMqttCallBack {
    
        /**
         * 收到消息
         *
         * @param topic   主题
         * @param message 消息内容
         * @param qos     消息策略
         */
        void messageArrived(String topic, String message, int qos);
    
        /**
         * 连接断开
         *
         * @param arg0 抛出的异常信息
         */
        void connectionLost(Throwable arg0);
    
        /**
         * 传送完成
         *
         * @param arg0
         */
        void deliveryComplete(IMqttDeliveryToken arg0);
    
        /**
         * 连接成功
         *
         * @param arg0
         */
        void connectSuccess(IMqttToken arg0);
    
        /**
         * 连接失败
         *
         * @param arg0
         */
        void connectFailed(IMqttToken arg0, Throwable arg1);
    
    }
    

    7.使用

     private EasyMqttService easyMqttService;
     private void initMQTT() {
            EasyMqttMethod easyMqttMethod = new EasyMqttMethod();
            easyMqttService = easyMqttMethod.buildEasyMqttService();
    
            //获取数据
            easyMqttMethod.getMsg(new EasyMqttMethod.OnConnectListener() {
                @Override
                public void onConnectSuccess(String msg) {
    
                }
    
                @Override
                public void onConnectFailed(Exception e) {
    
                }
            });
        }
    

    8.发送

    //发送MQTT信息
                new EasyMqttMethod().publishString("msg", "RelayUAVGround", 0, false, easyMqttService);
    
    展开全文
  • android mqtt

    2017-12-22 13:47:09
    package com.example.com.mqtt.simple.chat;import android.app.Activity; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.os.Message; import android....
    package com.example.com.mqtt.simple.chat;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.CountDownTimer;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    
    import com.example.com.mqtt.simple.utils.MqttClientService;
    import com.ibm.micro.client.mqttv3.MqttException;
    import com.ibm.micro.client.mqttv3.MqttPersistenceException;
    import com.ibm.micro.client.mqttv3.MqttSecurityException;
    
    public class MainActivity extends Activity {
        private EditText message_et;//消息内容
        private EditText password_et;//密码
        private EditText user_name_et;//用户名
        private EditText topic_et;//主题
        private EditText host_name_et;//mqtt地址
        private EditText receive_et;//接收内容
        private EditText client_id_et;//客户id
        private EditText subscribe_et;//订阅
        private TextView state_tv;//状态
    
        private Button connect_bt;//连接
        private Button submit_bt;//发送
        private Button subscribe_bt;
    
        private MqttClientService service;//mqtt服务
        private int failedCount=0;//失败次数
        protected final int MAX_FAILED_COUNT = 3 ;//最高失败次数
        public Handler handler;//ui 处理
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            initView();
            initViewValue();
            initHandler();
            //initMqtt();
            reload();
            initListen();
        }
        public void reload(){
            failedCount++;
            initMqtt();
            new CountDownTimer(5000, 1000) {
                @Override
                public void onTick(long arg0) {}
                @Override
                public void onFinish() {
                    if(failedCount>MAX_FAILED_COUNT ){
                        if(service!=null&&service.isConnect()){
                            return;
                        }
                        state_tv.setText("mqtt状态:未连接 ( "+failedCount+" 次重新连接失败!)");
                        return;
                    }
                    if(service==null || !service.isConnect()){
                        reload();
                    }
                }
            }.start();
        }
        private void initView(){
            state_tv = (TextView)findViewById(R.id.state_tv);
            connect_bt=(Button)findViewById(R.id.connect_bt);
            host_name_et=(EditText)findViewById(R.id.host_name_et);
            topic_et=(EditText)findViewById(R.id.topic_et);
            user_name_et=(EditText)findViewById(R.id.user_name_et);
            password_et=(EditText)findViewById(R.id.password_et);
            message_et=(EditText)findViewById(R.id.message_et);
            submit_bt=(Button)findViewById(R.id.submit_bt);
            receive_et=(EditText)findViewById(R.id.receive_et);
            client_id_et=(EditText)findViewById(R.id.client_id_et);
            subscribe_et=(EditText)findViewById(R.id.subscribe_et);
            subscribe_bt=(Button)findViewById(R.id.subscribe_bt);
        }
        private void initViewValue() {
            host_name_et.setText("tcp://192.168.0.107:61613");
            topic_et.setText("bxh");
            user_name_et.setText("admin");
            password_et.setText("password");
            message_et.setText("password");
            subscribe_et.setText("bxh");
        }
        private void initHandler() {
            handler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                    case 1:
                        state_tv.setText("mqtt状态:未连接");
                        connect_bt.setClickable(true);
                        failedCount=0;
                        reload();
                        break;
                    case 2:
                        //connect_bt.setClickable(false);
                        state_tv.setText("mqtt状态:已连接");
                        break;
                    case 3:
                        receive_et.setText(msg.getData().getString("msg"));
                        break;
                    case 4:
                        client_id_et.setText(msg.getData().getString("clientId"));
                        break;
                    default:
                        break;
                    }
    
                }
            };
        }
        private void initMqtt() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        service = MqttClientService.getInstance(
                                host_name_et.getText().toString().trim(),
                                user_name_et.getText().toString().trim(),
                                password_et.getText().toString().trim(),
                                handler
                                );
                        service.subscribe("bxh");//订阅
    
                        Message msg =new Message();
                        msg.what=2;
                        handler.sendMessage(msg);//不出exception 连接成功
                        return;
                    } catch (MqttSecurityException e) {
                        Log.e("e", e.getMessage());
                    } catch (MqttException e) {
                        Log.e("e", e.getMessage());
                    }
                }
            }).start();
        }
        private void initListen() {//添加监听
            submit_bt.setOnClickListener(new OnClickListener() {//发送
    
                @Override
                public void onClick(View arg0) {
                    String topic = topic_et.getText().toString().trim();
                    String msg = message_et.getText().toString().trim();
                    if ("".equals(topic)||"".equals(msg)) {
                        return;
                    }
                    try {
                        service.publish(topic, msg);//推送
                    } catch (MqttPersistenceException e) {
                        Log.e("e", e.getMessage());
                    } catch (MqttException e) {
                        Log.e("e", e.getMessage());
                    }
                }
            });
    
            connect_bt.setOnClickListener(new OnClickListener() {//连接
    
                @Override
                public void onClick(View arg0) {
                    reload();
                }
            });
            subscribe_bt.setOnClickListener(new OnClickListener() {//订阅
    
                @Override
                public void onClick(View arg0) {
                    if (service!=null&&service.isConnect()) {
                        String topicName = subscribe_et.getText().toString().trim();
                        if(!"".equals(topicName)){
                            try {
                                service.subscribe(topicName);
                                subscribe_et.setText("");
                            } catch (MqttSecurityException e) {
                                Log.e("e", e.getMessage());
                            } catch (MqttException e) {
                                Log.e("e", e.getMessage());
                            }
                        }
                    }
                }
            });
    
        }
    }
    
    package com.example.com.mqtt.simple.utils;
    
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.Map;
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    
    import com.ibm.micro.client.mqttv3.MqttCallback;
    import com.ibm.micro.client.mqttv3.MqttClient;
    import com.ibm.micro.client.mqttv3.MqttConnectOptions;
    import com.ibm.micro.client.mqttv3.MqttDeliveryToken;
    import com.ibm.micro.client.mqttv3.MqttException;
    import com.ibm.micro.client.mqttv3.MqttMessage;
    import com.ibm.micro.client.mqttv3.MqttPersistenceException;
    import com.ibm.micro.client.mqttv3.MqttSecurityException;
    import com.ibm.micro.client.mqttv3.MqttTopic;
    import com.ibm.micro.client.mqttv3.internal.MemoryPersistence;
    
    public class MqttClientService {
    
            private String host = "tcp://127.0.0.1:61613";
            private String clientid ; 
            private String userName = "admin";
            private String passWord = "password";
    
            private MqttClient client;  
            private MqttConnectOptions options; 
    
            private static MqttClientService instance;//单例
    
            private Map topicMap;//主题 map (去重复)
    
            private Handler handler;
    
            public void init() throws MqttSecurityException, MqttException {
                topicMap = new HashMap();
    
                clientid =System.currentTimeMillis()+"";//用户id 用当前时间
    
                client = new MqttClient(host, clientid, new MemoryPersistence());
    
                options = new MqttConnectOptions();  
                options.setUserName(userName);  
                options.setPassword(passWord.toCharArray()); 
                options.setCleanSession(true);
                options.setConnectionTimeout(10);  
                options.setKeepAliveInterval(20);
    
                client.setCallback(new PushCallback());
                //MqttTopic topic = client.getTopic("bxh");
                //options.setWill(topic, "Will".getBytes(), 2, true);
    
                client.connect(options);
    
                Message msg = new Message();
                Bundle data = new Bundle();
                data.putString("clientId", clientid);
                msg.setData(data);
                msg.what=4;
                handler.sendMessage(msg);//改变mainActivity 的cliendId
    
            }
    
            private MqttClientService(){}//单例
            private MqttClientService(String host,String userName,String password,Handler handler){
                this.host=host;
                this.userName=userName;
                this.passWord=password;
                this.handler=handler;
            }
            /**
             * 初始化service
             * @param host
             * @param userName
             * @param password
             * @param handler    ui 改变
             * @return
             * @throws MqttSecurityException
             * @throws MqttException
             */
            public static MqttClientService getInstance(String host,String userName,String password,Handler handler) throws MqttSecurityException, MqttException{
                if(instance==null){//单例
                    //instance = new MqttClientService();
                    instance = new MqttClientService(host,userName,password,handler);
                }
                instance.init();//连接服务器
                return instance;
            }
            /**
             * 消息推送
             * @param topicName  主题
             * @param message    消息
             * @throws MqttPersistenceException
             * @throws MqttException
             */
            public void publish(String topicName,String message) throws MqttPersistenceException, MqttException{
                client.getTopic(topicName).publish(new MqttMessage(message.getBytes()));
            }
            /**
             * 消息订阅
             * @param topicName    主题
             * @throws MqttSecurityException
             * @throws MqttException
             */
            public void subscribe(String topicName) throws MqttSecurityException, MqttException{
                topicMap.put(topicName,client.getTopic(topicName));//主题集合
    
                String[] topics= new String[topicMap.size()];
                int[] Qos  = new int[topicMap.size()];
    
                Arrays.fill(Qos, 1);
                topicMap.keySet().toArray(topics);
                client.subscribe(topics, Qos);
            }
            /**
             * 是否连接成功
             * @return
             */
            public boolean isConnect(){
                return client.isConnected();
            }
            /**
             * mqtt 回调
             * @author bxh
             *
             */
            class PushCallback implements MqttCallback {
                @Override
                public void connectionLost(Throwable cause) {
                    Message msg =new Message();
                    msg.what=1;
                    handler.sendMessage(msg);//通知失去连接
                }  
                @Override
                public void deliveryComplete(MqttDeliveryToken t) {
    
                }
                @Override
                public void messageArrived(MqttTopic topic, MqttMessage message) throws MqttException{
                    //System.out.println("接收消息主题 :" + topic);  
                    //System.out.println("接收消息 Qos:" + message.getQos());  
                    Message msg = new Message();
                    msg.what=3;
                    Bundle data = new Bundle();
                    data.putString("msg",  topic.getName()+": "+new String(message.getPayload()));
                    msg.setData(data);
                    handler.sendMessage(msg);//通知 消息到收到消息
                }  
            }
            /**
             * ui 改变
             * @param handler
             */
            public void setHandler(Handler handler){
                this.handler=handler;
            }
    }
    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.example.com.mqtt.simple.chat.MainActivity" >
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="mqtt状态:未连接"
            android:id="@+id/state_tv"
        />
    
    
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="mqtt地址"
        />
        <EditText 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/host_name_et"
            />
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="主题"
        />
        <EditText 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
             android:id ="@+id/topic_et"
            />
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="用户名"
        />
        <EditText 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
             android:id ="@+id/user_name_et"
            />
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
    
            android:text="密码"
        />
        <EditText 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
             android:id ="@+id/password_et"
             android:password="true"
            />
    
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="客户id"
        />
         <EditText 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
             android:id ="@+id/client_id_et"
            />
         <Button 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id ="@+id/connect_bt"
            android:text="连接"
           />
    
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="订阅"
        />
         <EditText 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
             android:id ="@+id/subscribe_et"
            />
    
    
        <Button 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id ="@+id/subscribe_bt"
            android:text="订阅"
           />
    
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="消息内容"
        />
        <EditText 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
             android:id ="@+id/message_et"
            />
        <Button 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id ="@+id/submit_bt"
            android:text="发送"
           />
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="接收内容"
        />
        <EditText 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
             android:id ="@+id/receive_et"
            />
    </LinearLayout>
    
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.com.mqtt.simple.chat"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="14"
            android:targetSdkVersion="21" />
    
    
    
    
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
    </manifest>
    
    展开全文
  • Android Mqtt

    千次阅读 2016-02-28 19:08:45
    本文介绍在Android上使用mqtt,附上客户端demo和服务器demo。 mqtt资料自行百度 客户端: 别忘了加联网权限 public class MqttService extends Service { private String host = "tcp://192.168.1.184:1883"; ...

    本文介绍在Android上使用mqtt,附上客户端demo和服务器demo。

    mqtt资料自行百度

    客户端:

    别忘了加联网权限

    public class MqttService extends Service {
    
        
        private String host = "tcp://192.168.1.184:1883";
        private String userName = "admin";
        private String passWord = "password";
    
        private Handler handler;
    
        private MqttClient client;
    
        private String myTopic = "test/topic";
    
        private MqttConnectOptions options;
    
        private ScheduledExecutorService scheduler;
    
        public MqttService</span>() {
            super();
        }
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.i("Gmw", "onCreate");
            init();
    
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if (msg.what == 1) {
                        Log.i("Gmw", "" + (String) msg.obj);
                        
                    } else if (msg.what == 2) {
                        Log.i("Gmw", "连接成功");
                        try {
                            client.subscribe(myTopic, 1);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (msg.what == 3) {
                        Log.i("Gmw", "连接失败,系统正在重连");
                    }
                }
            };
    
            startReconnect();
        }
    
    
        private void startReconnect() {
            scheduler = Executors.newSingleThreadScheduledExecutor();
            scheduler.scheduleAtFixedRate(new Runnable() {
    
                @Override
                public void run() {
                    if (!client.isConnected()) {
                        connect();
                    }
                }
            }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
        }
    
        private void init() {
            try {
                //host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
                client = new MqttClient(host, "lalalalalal",
                        new MemoryPersistence());
                //MQTT的连接设置
                options = new MqttConnectOptions();
                //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
                options.setCleanSession(true);
                //设置连接的用户名
                options.setUserName(userName);
                //设置连接的密码
                options.setPassword(passWord.toCharArray());
                // 设置超时时间 单位为秒
                options.setConnectionTimeout(10);
                // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
                options.setKeepAliveInterval(20);
                //设置回调
                client.setCallback(new MqttCallback() {
    
                    @Override
                    public void connectionLost(Throwable cause) {
                        //连接丢失后,一般在这里面进行重连
                        Log.i("Gmw", "connectionLost");
                    }
    
                    @Override
                    public void deliveryComplete(IMqttDeliveryToken token) {
                        //publish后会执行到这里
                        Log.i("Gmw", "deliveryComplete");
                    }
    
                    @Override
                    public void messageArrived(String topicName, MqttMessage message)
                            throws Exception {
                        //subscribe后得到的消息会执行到这里面
                        Log.i("Gmw", "messageArrived");
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = topicName + "---" + message.toString();
                        handler.sendMessage(msg);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private void connect() {
            new Thread(new Runnable() {
    
                @Override
                public void run() {
                    try {
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 2;
                        handler.sendMessage(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Message msg = new Message();
                        msg.what = 3;
                        handler.sendMessage(msg);
                    }
                }
            }).start();
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.i("Gmw", "onDestroy");
            try {
                scheduler.shutdown();
                client.disconnect();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }


    服务器:

    ActiveMQ,下载地址:http://activemq.apache.org/download.html

    下载后cd到/bin/macosx/activemq 目录  输入命令:./activemq start 启动服务器项目

    打开浏览器 localhost:8161   能启动正常就说明服务器启动成功了

    运行客户端代码连接服务器,然后用服务器给客户端推动信息

    展开全文
  • android MQTT

    2016-04-07 11:21:11
    Android推送方案分析(MQTT/XMPP/GCM) 蜗牛TT 发布于 3年前,共有 15 条评论 本文主旨在于,对目前Android平台上最主流的几种消息推送方案进行分析和对比,比较客观地反映出这些推送方案的优缺点,帮助大家选择...
    Android推送方案分析(MQTT/XMPP/GCM) 
    

    蜗牛TT 发布于 3年前,共有 15 条评论

    本文主旨在于,对目前Android平台上最主流的几种消息推送方案进行分析和对比,比较客观地反映出这些推送方案的优缺点,帮助大家选择最合适的实施方案。

    方案1、 使用GCM服务(Google Cloud Messaging)
    简介:Google推出的云消息服务,即第二代的G2DM。
    优点:Google提供的服务、原生、简单,无需实现和部署服务端。
    缺点:Android版本限制(必须大于2.2版本),该服务在国内不够稳定、需要用户绑定Google帐号,受限于Google。

    方案2、 使用XMPP协议(Openfire + Spark + Smack)
    简介:基于XML协议的通讯协议,前身是Jabber,目前已由IETF国际标准化组织完成了标准化工作。
    优点:协议成熟、强大、可扩展性强、目前主要应用于许多聊天系统中,且已有开源的Java版的开发实例androidpn。
    缺点:协议较复杂、冗余(基于XML)、费流量、费电,部署硬件成本高。

    方案3、 使用MQTT协议(更多信息见: http://mqtt.org/
    简介:轻量级的、基于代理的“发布/订阅”模式的消息传输协议。
    优点:协议简洁、小巧、可扩展性强、省流量、省电,目前已经应用到企业领域(参考: http://mqtt.org/software ),且已有C++版的服务端组件rsmb。
    缺点:不够成熟、实现较复杂、服务端组件rsmb不开源,部署硬件成本较高。

    方案4、 使用HTTP轮循方式
    简介:定时向HTTP服务端接口(Web Service API)获取最新消息。
    优点:实现简单、可控性强,部署硬件成本低。
    缺点:实时性差。

    对各个方案的优缺点的研究和对比,推荐使用MQTT协议的方案进行实现,主要原因是: MQTT最快速,也最省流量(固定头长度仅为2字节),且极易扩展,适合二次开发 。接下来,我们就来分析使用MQTT方案进行Android消息的原理和方法,并架设自己的推送服务。

    1、推送原理分析




    实际上,其他推送系统(包括GCM、XMPP方案)的原理都与此类似。

    2、推送服务端准备

    a> 下载&解压rsmb安装包(下载地址: http://www.alphaworks.ibm.com/tech/rsmb
    b> 进入对应的目录,比如32位的Linux系统则应该进入linux_ia32目录。
    c> 编辑配置文件broker_1883.cfg,配置如下:
    1. port 1883  
    2. max_inflight_messages 10  
    3. max_queued_messages 1000  
    d> 运行./broker broker_1883.cfg,显示如下:
    20120823 110454.039 CWNAN9999I Really Small Message Broker
    20120823 110454.039 CWNAN9997I Licensed Materials - Property of IBM
    20120823 110454.039 CWNAN9996I Copyright IBM Corp. 2007, 2010 All Rights Reserved
    20120823 110454.039 CWNAN9995I US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
    20120823 110454.039 CWNAN0049I Configuration file name is broker_1883.cfg
    20120823 110454.040 CWNAN0053I Version 1.2.0, Aug 18 2010 17:03:35
    20120823 110454.040 CWNAN0054I Features included: bridge
    20120823 110454.040 CWNAN9993I Author: Ian Craggs (icraggs@uk.ibm.com)
    20120823 110454.040 CWNAN0014I MQTT protocol starting, listening on port 1883
    ... ...
    这样,推送服务的服务端就已经准备好了,监听1883端口。

    3、推送客户端准备

    a> 下载&解压AndroidPushNotificationsDemo项目(下载地址: https://github.com/tokudu/AndroidPushNotificationsDemo
    b> 将该项目导入Eclipse中(File -> Export -> Existing Projects into Workspace)
    c> 修改PushService.java中的 MQTT_HOST 常量为推送服务端的IP地址。
    d> 启动Android模拟器,并安装该项目。

    注意: 在新版本的Android SDK中可能会遇到以下错误。
    ... ...
    08-23 02:28:44.184: W/dalvikvm(282): VFY: unable to find class referenced in signature (Lcom/ibm/mqtt/MqttPersistence;)
    08-23 02:28:44.194: I/dalvikvm(282): Failed resolving Lcom/tokudu/demo/PushService$MQTTConnection; interface 35 'Lcom/ibm/mqtt/MqttSimpleCallback;'
    08-23 02:28:44.194: W/dalvikvm(282): Link of class 'Lcom/tokudu/demo/PushService$MQTTConnection;' failed
    08-23 02:28:44.194: E/dalvikvm(282): Could not find class 'com.tokudu.demo.PushService$MQTTConnection', referenced from method com.tokudu.demo.PushService.connect
    08-23 02:28:44.194: W/dalvikvm(282): VFY: unable to resolve new-instance 42 (Lcom/tokudu/demo/PushService$MQTTConnection;) in Lcom/tokudu/demo/PushService;
    ... ...
    08-23 02:28:44.404: E/AndroidRuntime(282): java.lang.VerifyError: com.tokudu.demo.PushService
    08-23 02:28:44.404: E/AndroidRuntime(282):     at com.tokudu.demo.PushActivity$1.onClick(PushActivity.java:32)
    08-23 02:28:44.404: E/AndroidRuntime(282):     at android.view.View.performClick(View.java:2408)
    08-23 02:28:44.404: E/AndroidRuntime(282):     at android.view.View$PerformClick.run(View.java:8816)
    08-23 02:28:44.404: E/AndroidRuntime(282):     at android.os.Handler.handleCallback(Handler.java:587)
    08-23 02:28:44.404: E/AndroidRuntime(282):     at android.os.Handler.dispatchMessage(Handler.java:92)
    08-23 02:28:44.404: E/AndroidRuntime(282):     at android.os.Looper.loop(Looper.java:123)
    08-23 02:28:44.404: E/AndroidRuntime(282):     at android.app.ActivityThread.main(ActivityThread.java:4627)
    08-23 02:28:44.404: E/AndroidRuntime(282):     at java.lang.reflect.Method.invokeNative(Native Method)
    08-23 02:28:44.404: E/AndroidRuntime(282):     at java.lang.reflect.Method.invoke(Method.java:521)
    08-23 02:28:44.404: E/AndroidRuntime(282):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    08-23 02:28:44.404: E/AndroidRuntime(282):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    08-23 02:28:44.404: E/AndroidRuntime(282):     at dalvik.system.NativeStart.main(Native Method)
    ... ...
    原因是发布的时候没有加入wmqtt.jar包,解决办法如下:
    1> 在项目根目录下创建libs目录,并把wmqtt.jar包移入该目录。
    2> 重新配置项目的Java Build Path(右键菜单中的Properties选项中)。
    3> 重新打包发布即可。

    运行效果如下:



    点击“Start Push Service”按钮即可开启推送服务。这时我们可以看到rsmb的服务日志中打出以下提示:
    20120823 113742.297 CWNAN0033I Connection attempt to listener 1883 received from client tokudu/9774d56d682e549c on address 192.168.28.39:3345
    其中的“9774d56d682e549c”就是对应的客户端ID号。

    4、发送服务准备

    a> 下载&解压PHP版的发送服务端代码send_mqtt.zip(下载地址: http://download.csdn.net/detail/shagoo/4520102
    b> 修改etc/config.php中推送服务端的IP地址和端口号,即 MQTT_SERVER_HOST MQTT_SERVER_POST 常量。
    c> 打开对应的URL地址,就可以看到发送服务的界面,实际上就是向对应的推送客户端推送消息。



    接着,我们在该界面中填入客户端ID(9774d56d682e549c)和推送消息(test)并点击“Send Push Message”按钮,服务端就可以向客户端推送消息了。我们看到,客户端上立马就可以收到刚刚推送的消息,如下图。



    当然,以上方案还存在许多的不足,比如,如果客户端没有保持连接,发送的消息就会被丢弃。不过,我们可以利用MQTT协议开发出更强大的服务端来替代rsmb,更可以加入队列、缓存等功能进行优化,有兴趣的朋友不妨试试。可参考开源项目 Mosquitto http://mosquitto.org/ ),相关内容我们会在下一篇《 Mosquitto服务的安装与使用 》中介绍。
    展开全文
  • android MQTT的使用及demo

    2018-07-18 16:54:37
    android MQTT的使用及demoandroid MQTT的使用及demoandroid MQTT的使用及demo
  • E/AndroidRuntime(282): at android.view.View.performClick(View.java:2408)08-23 02:28:44.404: E/AndroidRuntime(282): at android.view.View$PerformClick.run(View.java:8816)08-23 02:28:44.404: E/Android...
  • Android MQTT客服端程序

    2021-01-08 18:28:55
    Android MQTT客服端程序,包括了连接服务器,断线重连,订阅消息,处理消息,发布消息,修改了断开连接disconnect报错
  • Android mqtt协议 推送

    2016-10-25 22:42:59
    Android mqtt协议 推送 带各种服务端
  • Android MQTT消息推送

    2012-02-07 15:37:52
    Android MQTT消息推送Android MQTT消息推送
  • android mqtt demo 推送

    2014-02-19 13:17:51
    android mqtt demo 推送
  • Android MQTT的使用

    2020-12-30 20:20:32
    Android MQTT的使用
  • Android-MQTT
  • Android MQTT 使用详解

    2020-11-26 16:50:05
    Android MQTT 使用详解MQTT 使用引入MQTT库MqttManagerMqttCallbackBus MQTT 使用 引入MQTT库 //MQTT implementation ‘org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0’ implementation ‘org.eclipse....
  • android mqtt客户端源码,可以安装直接使用,bin目录下面有*apk 安装即可,并可以结合服务端Mosquitto 畅快使用学习研究
  • android MQTT 带SSL加密连接例子demo 安卓使用BKS加密文件进行SSL加密MQTT连接
  • Android MQTT 使用的坑

    千次阅读 2018-09-13 18:59:54
    Android MQTT 使用的坑 Android studio 3.1.2 大概说一下场景: 我并不是直接用org.eclipse.paho.client.mqttv3-1.2.1.jar,而且在moduleA中创建了mqtt业务组件, 打包成A.aar ,再在app中引入使用aar。 经过...
  • Android MQTT code

    2019-03-30 23:54:03
    连接onenet需要的jar,OneNET-MQTT-sdk.jar,chinamobile
  • AndroidMqtt源码

    2017-03-03 14:12:35
    Mqtt源码
  • Android MQTT学习总结以及用法前言MQTT是什么MQTT原理Android中使用MQTT 前言 记录在开发中学习,使用MQTT的经验,以及遇到的坑 MQTT是什么 先上一段百度百科的说明 MQTT(消息队列遥测传输)是ISO 标准(ISO/IEC ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 6,366
精华内容 2,546
关键字:

androidmqtt