Android 泛美卫生组织发布大延迟

Android paho publish big delay

我正在尝试在 android 中编写一个应用程序来发布 mqtt 消息。 我正在使用 AsyncTask 来发布到我的经纪人,但有时我会有很大的延迟,我猜是因为我每次都必须在发布之前连接到经纪人

@Override
protected Void doInBackground(String... params) {

    try {
        settings = new AppSettings(context);

        if (!settings.getBroker().isEmpty()) {

            client = new MqttClient(settings.getBroker(), MQTTService.ANDROID_ID, new MemoryPersistence());

            if (!settings.getUsername().isEmpty() || settings.getPassword().isEmpty()) {
                MqttConnectOptions options = new MqttConnectOptions();
                options.setUserName(settings.getUsername());
                options.setPassword(settings.getPassword().toCharArray());
                client.setCallback(new MQTTPushCallback(context));
                client.connect(options);
            } else {
                client.setCallback(new MQTTPushCallback(context));
                client.connect();
            }

            if (client.isConnected()) {
                client.publish(settings.getTopic(), new MqttMessage(params[0].getBytes()));
            } else {
                Log.d(TAG, "Client is not connected to the mqtt service");
            }

        } else {
            Log.d(TAG, "Broker URL unavailable !");
        }

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

    return null;
}

我的问题是,是否有更好的方法来做到这一点,也许在服务中保持连接活动?

此致,
保罗.

在 paho 站点 (https://eclipse.org/paho/clients/android/) 上有一个 Android 服务,你真的应该使用它来保持连接打开和实时,然后只发布数据

好的,事实证明这很简单,我所做的就是创建一个子 class 并扩展 BroadcastReceiver

public class PublishBroadcast extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG , "onReceive");
        if((client != null) && (client.isConnected())){
            String Payload = intent.getStringExtra(EXTRA_MESSAGE);
            MqttMessage message = new MqttMessage(Payload.getBytes());
            try {
                client.publish(TOPIC ,message);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }
}

比起在我的服务中的 onCreate(),我已经注册了接收器

LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(new PublishBroadcast() ,
            new IntentFilter(ACTION_PUBLISH));