android MQTT通信 簡(jiǎn)單使用

一,在app下的build.gradle中添加如下引用

    implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'//mqtt相關(guān)
    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'//mqtt相關(guān)
    implementation 'org.greenrobot:eventbus:3.1.1'//eventBus  為了傳數(shù)據(jù)會(huì)UI界面

二,AndroidManifest.xml中添加權(quán)限

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

在application中添加如下代碼

   <service android:name="org.eclipse.paho.android.service.MqttService" /> <!--MqttService-->
   <service android:name=".service.MyMqttService"/> <!--MyMqttService  自己寫的服務(wù)  后面會(huì)講-->

三,MyMqttService類

public class MyMqttService extends Service {

    public final String TAG = MyMqttService.class.getSimpleName();
    private static MqttAndroidClient mqttAndroidClient;
    private MqttConnectOptions mMqttConnectOptions;
    public String HOST = "tcp://192.168.101.115:1883";//服務(wù)器地址(協(xié)議+地址+端口號(hào))
    public String USERNAME = "admin";//用戶名
    public String PASSWORD = "admin";//密碼
    public static String PUBLISH_TOPIC = "tourist_enter";//發(fā)布主題
    public static String RESPONSE_TOPIC = "message_arrived";//響應(yīng)主題
    public String CLIENTID = "zhangrenwen";
//    public String CLIENTID = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
//            ? Build.getSerial() : Build.SERIAL;//客戶端ID,一般以客戶端唯一標(biāo)識(shí)符表示,這里用設(shè)備序列號(hào)表示

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        init();
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 開啟服務(wù)
     */
    public static void startService(Context mContext) {
        mContext.startService(new Intent(mContext, MyMqttService.class));
    }

    /**
     * 發(fā)布 (模擬其他客戶端發(fā)布消息)
     *
     * @param message 消息
     */
    public static void publish(String message) {
        String topic = PUBLISH_TOPIC;
        Integer qos = 2;
        Boolean retained = false;
        try {
            //參數(shù)分別為:主題、消息的字節(jié)數(shù)組、服務(wù)質(zhì)量、是否在服務(wù)器保留斷開連接后的最后一條消息
            mqttAndroidClient.publish(topic, message.getBytes("GBK"), qos.intValue(), retained.booleanValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 響應(yīng) (收到其他客戶端的消息后,響應(yīng)給對(duì)方告知消息已到達(dá)或者消息有問題等)
     *
     * @param message 消息
     */
    public void response(String message) {
        String topic = RESPONSE_TOPIC;
        Integer qos = 2;
        Boolean retained = false;
        try {
            //參數(shù)分別為:主題、消息的字節(jié)數(shù)組、服務(wù)質(zhì)量、是否在服務(wù)器保留斷開連接后的最后一條消息
            mqttAndroidClient.publish(topic, message.getBytes(), qos.intValue(), retained.booleanValue());
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化
     */
    private void init() {
        String serverURI = HOST; //服務(wù)器地址(協(xié)議+地址+端口號(hào))
        mqttAndroidClient = new MqttAndroidClient(this, serverURI, CLIENTID);
        mqttAndroidClient.setCallback(mqttCallback); //設(shè)置監(jiān)聽訂閱消息的回調(diào)
        mMqttConnectOptions = new MqttConnectOptions();
        mMqttConnectOptions.setCleanSession(true); //設(shè)置是否清除緩存
        mMqttConnectOptions.setConnectionTimeout(10); //設(shè)置超時(shí)時(shí)間,單位:秒
        mMqttConnectOptions.setKeepAliveInterval(20); //設(shè)置心跳包發(fā)送間隔,單位:秒
        mMqttConnectOptions.setUserName(USERNAME); //設(shè)置用戶名
        mMqttConnectOptions.setPassword(PASSWORD.toCharArray()); //設(shè)置密碼

        // last will message
        boolean doConnect = true;
        String message = "{\"terminal_uid\":\"" + CLIENTID + "\"}";
        String topic = PUBLISH_TOPIC;
        Integer qos = 2;
        Boolean retained = false;
        if ((!message.equals("")) || (!topic.equals(""))) {
            // 最后的遺囑
            try {
                mMqttConnectOptions.setWill(topic, message.getBytes(), qos.intValue(), retained.booleanValue());
            } catch (Exception e) {
                Log.i(TAG, "Exception Occured", e);
                doConnect = false;
                iMqttActionListener.onFailure(null, e);
            }
        }
        if (doConnect) {
            doClientConnection();
        }
    }

    /**
     * 連接MQTT服務(wù)器
     */
    private void doClientConnection() {
        if (!mqttAndroidClient.isConnected() && isConnectIsNomarl()) {
            try {
                mqttAndroidClient.connect(mMqttConnectOptions, null, iMqttActionListener);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判斷網(wǎng)絡(luò)是否連接
     */
    private boolean isConnectIsNomarl() {
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            String name = info.getTypeName();
            Log.i(TAG, "當(dāng)前網(wǎng)絡(luò)名稱:" + name);
            return true;
        } else {
            Log.i(TAG, "沒有可用網(wǎng)絡(luò)");
            /*沒有可用網(wǎng)絡(luò)的時(shí)候,延遲3秒再嘗試重連*/
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    doClientConnection();
                }
            }, 3000);
            return false;
        }
    }

    //MQTT是否連接成功的監(jiān)聽
    private IMqttActionListener iMqttActionListener = new IMqttActionListener() {

        @Override
        public void onSuccess(IMqttToken arg0) {
            Log.i(TAG, "連接成功 ");
            try {
                mqttAndroidClient.subscribe(PUBLISH_TOPIC, 2);//訂閱主題,參數(shù):主題、服務(wù)質(zhì)量
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(IMqttToken arg0, Throwable arg1) {
            arg1.printStackTrace();
            Log.i(TAG, "連接失敗 ");
            doClientConnection();//連接失敗,重連(可關(guān)閉服務(wù)器進(jìn)行模擬)
        }
    };

    //訂閱主題的回調(diào)
    private MqttCallback mqttCallback = new MqttCallback() {

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            Log.i(TAG, "收到消息: " + topic + new String(message.getPayload(),"GBK"));
            EventBus.getDefault().post(new UpdateTextEvent(new String(message.getPayload(),"GBK")));
            //收到消息,這里彈出Toast表示。如果需要更新UI,可以使用廣播或者EventBus進(jìn)行發(fā)送
//            Toast.makeText(getApplicationContext(), "messageArrived: " + new String(message.getPayload()), Toast.LENGTH_LONG).show();
            //收到其他客戶端的消息后,響應(yīng)給對(duì)方告知消息已到達(dá)或者消息有問題等
            response("message arrived");
        }


        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0) {

        }

        @Override
        public void connectionLost(Throwable arg0) {
            Log.i(TAG, "連接斷開 ");
            doClientConnection();//連接斷開,重連
        }
    };

    @Override
    public void onDestroy() {
        try {
            mqttAndroidClient.disconnect(); //斷開連接
            Log.i(TAG, "onDestroy: 服務(wù)關(guān)閉");
        } catch (MqttException e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }
}

四,封裝數(shù)據(jù)bean類

public class UpdateTextEvent {
    private static final String TAG = "AA";
    private String msg;

    public UpdateTextEvent(String msg) {
        this.msg = msg;
        Log.i(TAG, "updateTextEvent: " + msg);
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

五,activity_main.xml布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="發(fā)送"
        app:layout_constraintTop_toBottomOf="@+id/editText"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintTop_toBottomOf="@+id/button"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        />

</android.support.constraint.ConstraintLayout>

六,MainActivity代碼

public class MainActivity extends AppCompatActivity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText editText = findViewById(R.id.editText);

        textView = findViewById(R.id.textView);
        MyMqttService.startService(this); //開啟服務(wù)
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyMqttService.publish(editText.getText().toString());
            }
        });
    }

    /**
     * 訂閱的過程中,默認(rèn)是在主線程中用到的
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void modifyBtn4(UpdateTextEvent msg) {
        textView.setText("收到的消息:"+msg.getMsg());
    }

    @Override
    public void onStart() {
        super.onStart();
        //在事件被訂閱的界面中注冊(cè)EventBus
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        //注銷EventBus
        EventBus.getDefault().unregister(this);
    }
}

至此 已經(jīng)完畢 但是想要測(cè)試效果請(qǐng)聯(lián)系后臺(tái)
我們根據(jù)后臺(tái)修改以下框框內(nèi)容就好


QQ截圖20190828151833.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容