三大块: 配置, 服务, 主程序
- MqttConfig
- MqttService
- MainActivity
- MQTT库 / AndroidManifest.xml
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'//版本号很多,随便选一个
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'//如果Broadcastmanager报错加这个
- 配置类: MqttConfig
public class MqttConfig {
private String serverURL;
private String userName;
private String passWord;
private String topic;
private String clientID;
public String getServerURL() {
return serverURL;
}
public void setServerURL(String serverURL) {
this.serverURL = serverURL;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getClientID() {
return clientID;
}
public void setClientID(String clientID) {
this.clientID = clientID;
}
public MqttConfig(String serverURL, String userName, String passWord, String topic, String clientID) {
this.serverURL = serverURL;
this.userName = userName;
this.passWord = passWord;
this.topic = topic;
this.clientID = clientID;
}
@Override
public String toString() {
return "MqttConfig{" +
"serverURL='" + serverURL + '\'' +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", topic='" + topic + '\'' +
", clientID='" + clientID + '\'' +
'}';
}
}
- MqttService
import ...
public class MyMqttService extends Service {
private static final String TAG = "testOfMqttService";
private MqttConfig mqttConfig;
private MqttAndroidClient client;
private MqttConnectOptions options;
/*
* Start Service
*/
public static void startService(Context mContext) {
mContext.startService(new Intent(mContext, MyMqttService.class));
Log.d(TAG, "startService: Service startService");
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
/*
* Initialize Mqtt Config
*/
Log.d(TAG, "onCreate: Service initMqtt");
initMqtt();
return super.onStartCommand(intent, flags, startId);
}
private void initMqtt() {
/*
* Main Mqtt Config
*/
mqttConfig = new MqttConfig(
"tcp://broker.emqx.io:1883", //换自己的地址, 记得加tcp://
"emq",
"public",
"AndroidTest",
"Android"
);
/*
* Set connection options
*/
options = new MqttConnectOptions();
options.setCleanSession(true);
options.setUserName(mqttConfig.getUserName());
options.setPassword(mqttConfig.getPassWord().toCharArray());
options.setConnectionTimeout(10);
options.setKeepAliveInterval(60);
/*
* Create and configure the client
*/
client = new MqttAndroidClient(this, mqttConfig.getServerURL(), mqttConfig.getClientID());
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
// will do after lost(reconnect)
Log.d(TAG, "connectionLost: Service");
Log.d(TAG, "connectionLost " + cause.getMessage());
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
// will do after messageArrived
Log.d(TAG, "messageArrived: Service");
Log.d(TAG, "Topic: " + topic + "messageArrived: " + new String(message.getPayload()));
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// will do after publish
Log.d(TAG, "deliveryComplete: Service");
Log.d(TAG, "deliveryComplete: " + token.toString());
}
});
boolean doConnect = true;
if (doConnect) {
mqttConnect();
}
}
// MQTT connection listener
private IMqttActionListener iMqttActionListener = new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
try {
// subscribe topic
client.subscribe(mqttConfig.getTopic(),2);
Log.d(TAG, "onSuccess: Service MQTT connection succeed");
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "onFailure: Service MQTT connection failed");
//reconnect
}
};
private void mqttConnect() {
try {
Log.d(TAG, "mqttConnect: Service try to connect");
client.connect(options, null, iMqttActionListener);
} catch (MqttException e) {
Log.d(TAG, "mqttConnect: Service try to connect failed");
e.printStackTrace();
}
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy: Service");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// // TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
return null;
}
}
- MainActivity
import ...
public class MainActivity extends AppCompatActivity {
private static final String TAG = "testOfMain" ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate: Main");
}
@Override
protected void onStart() {
super.onStart();
setContentView(R.layout.activity_main);
/*Start Service*/
Log.d(TAG, "onCreate: Main starts Service");
MyMqttService.startService(this);
}
}