java - 创建 Xmpp 连接并传递实例而无需重新创建的最佳方法

标签 java android android-studio xmpp xmppframework

我有一个名为 XmppChatManager 的类(class)其中具有所有必要的方法,例如 initializingConnection()sendOneToOneMessage() ,其他需要使用这个类的类需要做这样的事情:

XmppChatManager xmppchatmanager = new XmppChatManager(this, userId, password);

runOnUiThread(new Runnable() {
                public void run() {
                    Thread thread = new Thread(){
                        public void run(){
                            try {
                                xmppchatmanager.initializingConnection();
                            } catch (IOException e) {
                                e.printStackTrace();
                            } catch (XMPPException e) {
                                e.printStackTrace();
                            } catch (SmackException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    thread.start();
                }
            });

This is pretty much all I need to get started, the issue i'm having is when I try calling the sendOneToOneMessage() method from the chatClass, I have to get the instance of the created connection because Smack Error will occur if I try reconnecting when the connection is already initiated! So I need to make available the instance of that initiated connection by creating a method called getInstance() I guess this might be simple but I have tried but I'm not getting it. Any one with better way of handling such?

最佳答案

让你的xmppchatmanager成为单例,例如

public class XmppChatManager{
   static class Loader{
        static XmppChatManager sInstance = new XmppChatManaget();
   }

   public static XmppChatManager getInstance(){
        return Loader.sInstance;
   }
}

关于java - 创建 Xmpp 连接并传递实例而无需重新创建的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49888791/

相关文章:

android - 显示和关闭键盘后,TextInputLayout 错误文本未按预期显示

android - 我如何从 JSON 中获取国家和州并将其填充到 Spinner 上

java - 如何将链表添加到 vector 中?

java - 使用 GSON 将 JSON 文件中的数据解析为 Java 对象

android - 带有 mockito 测试的简单 kotlin 类导致 MissingMethodInvocationException

Android - 更改语言环境(语言)

java - 设置最新 Activity 信息

android-studio - 在 Android Studio 中配置导入顺序?

java - 状态 500 – Java Servlet 上的内部服务器错误

java - 收到 'else',但没有 'if' 错误