java - 当我在其他 Activity 中使用 mqtt 客户端时,他们向我显示错误

标签 java android mqtt paho

当我在其他 Activity 中使用 mqtt 客户端时,它们向我显示错误,当我在 OnDestroy 中关闭客户端然后在不同 Activity 中使用客户端时,它没有给出错误,但 setactioncallback 不起作用,它没有成功也没有失败

主要 Activity

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    username = findViewById(R.id.username);
    password = findViewById(R.id.password);
    login = findViewById(R.id.btn);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String clientId = MqttClient.generateClientId();
             client =
                    new MqttAndroidClient(MainActivity.this, "tcp://broker.hivemq.com:1883",
                            clientId);

            try {
                MqttConnectOptions options = new MqttConnectOptions();
                options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);

                IMqttToken token = client.connect();
                token.setActionCallback(new IMqttActionListener() {
                    @Override
                    public void onSuccess(IMqttToken asyncActionToken) {
                        // We are connected
                        Log.d(TAG, "onSuccess");

                        gotosubscribelist();
                    }

                    @Override
                    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                        // Something went wrong e.g. connection timeout or firewall problems
                        Log.d(TAG, "onFailure");

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

}

private void gotosubscribelist()
{
    Intent intent = new Intent(this,SubscribelistActivity.class);
    intent.putExtra("client", String.valueOf(client));
    startActivity(intent);
    finish();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    client.unregisterResources();
   client.close();
}

订阅 Activity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_subscribelist);

    try {
        MainActivity.client.connect();
    } catch (MqttException e) {
        e.printStackTrace();
    }

    channel = findViewById(R.id.channel);
    subscribe = findViewById(R.id.subscribe);

    mRec = (RecyclerView) findViewById(R.id.recyclerview);
    newlist = new ArrayList<>();
    adapter = new ChannelAdapter(this,newlist);

    linearLayoutManager = new LinearLayoutManager(getApplicationContext());
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

    mRec.setHasFixedSize(true);
    mRec.setLayoutManager(linearLayoutManager);
    mRec.setAdapter(adapter);

    subscribe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            subscribe();
        }
    });
}

private void subscribe()
{
    Log.e("hi","1");
    final String topic = channel.getText().toString();
    int qos = 1;
    try {
        IMqttToken subToken = MainActivity.client.subscribe(topic, qos);
        subToken.setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                Log.e("suc","create");
                newlist.add(topic);
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken,
                                  Throwable exception) {
             Log.e("e",exception.getMessage());

            }
        });

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

@Override
protected void onDestroy() {
    super.onDestroy();

    MainActivity.client.unregisterResources();
    MainActivity.client.close();
}

我的问题是,如果我在 onDestroy 中删除 client.unregisterResources 和 client.close 然后它会显示

E/ActivityThread: Activity com.example.mqtt.UI.MainActivity has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection@7ce0751 that was originally bound here
android.app.ServiceConnectionLeaked: Activity com.example.mqtt.UI.MainActivity has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection@7ce0751 that was originally bound here

当我将 client.unregisterResources 和 client.close 放在 onDestroy 中时,它没有显示错误,但在订阅功能中它没有运行 onsuccess 和 onfailure,请给出一些建议

channel Activity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_channel);

    try {
        MainActivity.client.connect();
        MainActivity.client.isConnected();
    } catch (MqttException e) {
        e.printStackTrace();
    }

    message = findViewById(R.id.msg);
    publish = findViewById(R.id.publish);

    name = getIntent().getExtras().get("currentchannelname").toString();

    Rec = (RecyclerView) findViewById(R.id.recyclerview_msg);
    newlist = new ArrayList<>();
    adapter = new msgAdapter(this,newlist);

    linearLayoutManager = new LinearLayoutManager(getApplicationContext());
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

    Rec.setHasFixedSize(true);
    Rec.setLayoutManager(linearLayoutManager);
    Rec.setAdapter(adapter);

    getmessage();

    publish.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            publishmsg();
        }
    });

}

private void publishmsg()
{
    String topic = name;
    String payload = message.getText().toString().trim();
    byte[] encodedPayload = new byte[0];
    try {
        encodedPayload = payload.getBytes("UTF-8");
        MqttMessage message = new MqttMessage(encodedPayload);
        MainActivity.client.publish(topic, message);
    } catch (UnsupportedEncodingException | MqttException e) {
        e.printStackTrace();
    }
}

private void getmessage()
{
    MainActivity.client.setCallback(new MqttCallback() {
        @Override
        public void connectionLost(Throwable cause) {

        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            newlist.add(message.toString());
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    });
    adapter.notifyDataSetChanged();
}

@Override
protected void onDestroy() {
    super.onDestroy();

    MainActivity.client.unregisterResources();
    MainActivity.client.close();
}

最佳答案

删除

@Override
protected void onDestroy() {
super.onDestroy();

MainActivity.client.unregisterResources();
MainActivity.client.close();
}

来自订阅 Activity

关于java - 当我在其他 Activity 中使用 mqtt 客户端时,他们向我显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57705089/

相关文章:

android - Spotify 安卓 SDK : Play offline tracks

android - 在 Android web 应用程序中实现 coverflow UI

spring - MQTT Apache Camel 路由错误导致应用程序停止

google-cloud-platform - Google IOT 后端多久更新一次设备状态?

java - SunPkcs11 实现的 64 位替代方案

java - NoiseInk 中的透明背景 (Java)

java - 使用集合比较字符串数组

java - 如何将多个 "SELECT"语句合并为一个?

android - 如何在android中重新启动时不关闭的警报通知

mqtt - 在 MQTT 中,经纪人如何收到客户的遗嘱通知?