java代码
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
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;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private MqttClient mqttClient;
private TextView connectionStatusTextView;
private ImageView ledStatusImageView;
private boolean isConnecting = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
//使用AsyncTask异步,当执行execute时会自动开辟一个线程
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionStatusTextView =(TextView) findViewById(R.id.connection_status_text_view);
ledStatusImageView = findViewById(R.id.ledStatusImageView);
Button connectBtn = findViewById(R.id.connectBtn);
connectBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!isConnecting) {
new ConnectTask().execute();
}
}
});
Button reconnectBtn = findViewById(R.id.reconnectBtn);
reconnectBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!isConnecting) {
new ReconnectTask().execute();
}
}
});
Button disconnectBtn = findViewById(R.id.disconnectBtn);
disconnectBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new DisconnectTask().execute();
}
});
Button toggleLedBtn = findViewById(R.id.toggleLED);
toggleLedBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new ToggleLedTask().execute("led1");
}
});
Button toggleLed2Btn = findViewById(R.id.toggleLED2);
toggleLed2Btn.setOnClickListener(new View.OnClickListener(