为什么我不能为整个 android 应用程序只使用一个 MqttAndroidClient?

Why i can't just have one MqttAndroidClient for the whole android application?

我有一个 Smarthome 毕业设计,它使用 MQTT 协议与云通信以及控制它的 android 应用程序。

我试图只创建一个 MqttAndroidClient 并在所有活动中使用它,但这不起作用,当我尝试将同一客户端传递给另一个客户端中的发布或订阅方法时出现错误 class

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.badr.said.muhammad.smarthome/com.badr.said.muhammad.smarthome.Welcome}: java.lang.NullPointerException: Attempt to invoke virtual method 'org.eclipse.paho.client.mqttv3.IMqttDeliveryToken org.eclipse.paho.android.service.MqttService.publish(java.lang.String, java.lang.String, byte[], int, boolean, java.lang.String, java.lang.String)' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)

这是发生错误的代码

public class Welcome extends AppCompatActivity {

MqttAndroidClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);

    client = new MqttAndroidClient(this.getApplicationContext(),mqtthost,clientId);
    MqttConnectOptions options = new MqttConnectOptions();
    options.setUserName(username);
    options.setPassword(password.toCharArray());

    try {
        IMqttToken token = client.connect(options);
        token.setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                Toast.makeText(Welcome.this, "Connected !", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                Toast.makeText(Welcome.this, "Connection Field , Check Your Internet Network !", Toast.LENGTH_LONG).show();

            }
        });

    } catch (MqttException e) {
        e.printStackTrace();
    }

    pub("Smarthome","check",client);
    sub5(client);

但是在某些将 MqttAndroidClient 作为参数传递的切换按钮上使用相同的 pub 和 sub5 方法,它的工作方式类似于此代码

toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                pub("Smarthome", "devicegon1", client);
            } else {
                pub("Smarthome", "devicegoff1", client);
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            sub();
        }
    });

怎么了,有什么想法或帮助吗?

您在调用 onSuccess() 之前调用了 pub(),因此您在尝试发布时尚未真正连接。

pub()sub5() 移动到那个回调中,事情应该会有所改善