前置
-
在
setting.gradle
里面添加java">maven { url ‘https://jitpack.io’ } maven { url ‘https://repo.eclipse.org/content/repositories/paho-releases/’}
java">pluginManagement { repositories { gradlePluginPortal() google() mavenCentral() } } dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() maven { url 'https://jitpack.io' } maven { url 'https://repo.eclipse.org/content/repositories/paho-releases/'} } } rootProject.name = "My Application" include ':app'
-
添加库
java">implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0' implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.0'
-
添加服务
java"><service android:name="org.eclipse.paho.android.service.MqttService" /> //自带服务
代码
main
java"> package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONObject;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MainActivity extends Activity {
private Handler handler;
private MqttClient client;
private MqttConnectOptions options;
private ScheduledExecutorService scheduler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText publishTopic = findViewById(R.id.publish_topic);
EditText subscribeTopic = findViewById(R.id.subscribe_topic);
EditText publishMessage = findViewById(R.id.publish_content);
EditText subscribeMessage = findViewById(R.id.subscribe_content);
Button connectServer = findViewById(R.id.connectServer);
Button publishButton = findViewById(R.id.publish);
Button subscribeButton = findViewById(R.id.subscribe);
MqttUtils mqttUtils = new MqttUtils();
mqttUtils.subscribeMsgEdit = subscribeMessage;
connectServer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mqttUtils.init();
mqttUtils.Mqtt_connect();
}
});
publishButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String topic = publishTopic.getText().toString();
String message = publishMessage.getText().toString();
mqttUtils.mqtt_pub_topic = topic;
mqttUtils.publishmessageplus(message);
}
});
subscribeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mqttUtils.mqtt_sub_topic= subscribeTopic.getText().toString();
mqttUtils.sub();
}
});
}
}
util
java">package com.example.myapplication;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
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 MqttUtils {
MqttUtils(){
this.host = "tcp://47.109.46.65:1883";
this.mqtt_id = "kafens_phone";
this.userName = "kafen";
this.passWord = "kafen";
}
public String host ;
public String mqtt_id ;
public String userName ;
public String passWord ;
public MqttClient client;
public String mqtt_sub_topic = "my_sub";
public String mqtt_pub_topic ="my_pub";
public String subscribeMsg;
public MqttConnectOptions options;
public ScheduledExecutorService scheduler;
public EditText subscribeMsgEdit;
public void init() {
try {
client = new MqttClient(host, mqtt_id, new MemoryPersistence());
options = new MqttConnectOptions();
options.setCleanSession(true);
options.setUserName(userName);
options.setPassword(passWord.toCharArray());
options.setConnectionTimeout(10);
options.setKeepAliveInterval(20);
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
System.out.println("connectionLost----------");
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("deliveryComplete---------" + token.isComplete());
}
@Override
public void messageArrived(String topicName, MqttMessage message) {
subscribeMsg = message.toString();
handler.sendEmptyMessage(3);
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
Handler handler = new Handler() {
@SuppressLint("SetTextIl8n")
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1: //开机校验更新回传
break;
case 2: //反馈回转
break;
case 3: //MQTT收到消息回传
subscribeMsgEdit.setText(subscribeMsg);
break;
case 30: //连接失败
// Toast.makeText(MainActivity.this,"连接失败",Toast.LENGTH_SHORT).show();
System.out.println("connect failed");
break;
case 31: //连接成功
// Toast.makeText(MainActivity.this,"连接成功",Toast.LENGTH_SHORT).show();
break;
case 92:
try {
client.subscribe(mqtt_sub_topic, 2);
} catch (MqttException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
};
public 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();
}
public 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 void publishmessageplus(String message2)
{
if (client == null || !client.isConnected()){
return;
}
MqttMessage message = new MqttMessage();
message.setPayload(message2.getBytes());
try {
client.publish(mqtt_pub_topic,message);
} catch (MqttException e) {
e.printStackTrace();
}
}
public void sub() {
try {
client.subscribe(mqtt_sub_topic, 2);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/publish_topic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Topic to publish"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/publish_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Input things to published"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/subscribe_topic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Topic to subscribe "
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/subscribe_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="This is what you will be received "
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/connectServer"
android:text="Connect to Server"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/subscribe"
android:text="Subscribe"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/publish"
android:text="Publish"/>
</LinearLayout>
工程下载
gitee下载