【问题标题】:How to use same XMPP connection through out the app如何在整个应用程序中使用相同的 XMPP 连接
【发布时间】:2014-02-08 08:52:25
【问题描述】:

我正在使用XMPPasmack 开发聊天应用程序。在启动时Activity 我想建立XMPP 连接,然后在不同的活动中使用它。但我不知道该怎么做。我搜索了很多,但找不到任何想要的解决方案。请指导我。

【问题讨论】:

    标签: android android-intent connection xmpp smack


    【解决方案1】:

    您可以将Connection 成员设为静态并选择允许其他活动访问该成员的访问级别修饰符关键字。

    但是,您通常不希望在 Activity 中处理 Connection,而是在扩展 Service 的类中处理。有很多使用 aSmack 的开源应用程序,看看它们的源代码。

    【讨论】:

    • 我已经在服务中创建了连接,但在活动中检索它时仍然遇到问题。
    • 正如我所说,您可以将 Connection 设为静态且对 Activity 可见。
    【解决方案2】:

    您可以使用此类设置连接并在其他活动中的任何位置获取它

    public class XMPPLogic {
    
      private XMPPConnection connection = null;
    
      private static XMPPLogic instance = null;
    
      public synchronized static XMPPLogic getInstance() {
        if(instance==null){
          instance = new XMPPLogic();
        }
        return instance;
      }
    
      public void setConnection(XMPPConnection connection){
        this.connection = connection;
      }
    
      public XMPPConnection getConnection() {
        return this.connection;
      }
    
    }
    

    并像这样设置连接..

    XMPPLogic.getInstance().setConnection(connection);
    

    并像这样获得连接..

    connection = XMPPLogic.getInstance().getConnection();
    

    【讨论】:

      【解决方案3】:

      您可以使用单例设计模式或创建一个实用程序类并将 xmpp 连接定义为静态,然后您可以在任何活动中使用它。

      对于单身人士这样做:

      public class MyConnection{
      private static MyConnection con;
      private MyConnection(){
      
              //ToDo here
      
      }
      public static MyConnection getInstance()
      {
          if (con == null)
         {
            MyConnection= new MyConnection();
         }
         return con;
         }
      
      }
      

      然后在任何活动中,您都可以通过键入 MyConnection.getInstance(); 来访问该对象

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-05
        • 2012-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-06
        • 2019-03-06
        相关资源
        最近更新 更多