【问题标题】:how to get same xmpp connection from one activity to another?如何从一项活动到另一项活动获得相同的 xmpp 连接?
【发布时间】:2011-11-25 18:56:32
【问题描述】:

我是新程序员。我想使用 xmpp 服务器实现用于聊天的示例应用程序。在此实现中,我使用 ConnectionConfiguration 对象创建了连接,如下所示:

ConnectionConfiguration connConfig =new ConnectionConfiguration(host, Integer.parseInt(sport), service);

我通过调用连接方法将 connConfig 对象传递给 XMPPConnection 类,我正在获取连接,并通过调用登录方法传递用户名和密码,然后我登录到密码。登录我使用的是按钮。当我点击按钮时我正在使用 Intent 更改活动。我正在更改活动,我想在另一个活动中获得相同的连接。

我为 LoginActivity 编写了如下代码:

  public class LoginActivity extends Activity
 {

ConnectionConfiguration connConfig ;

 XMPPConnection connection;



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


    ((Button)findViewById(R.id.login)).setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) 
           {

             connConfig =new ConnectionConfiguration(host, Integer.parseInt(sport), service);

          connection = new XMPPConnection(connConfig);

            connection.connect();
            connection.login(uname, password);

        }
});

 }
}

我写的ChatPageActivity如下:

     public class ChatPage extends Activity {

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.chatpage);

    //How to get the same XMPPConnection from LoginActivity here    

     }
  }

如何获得从 LoginActivity 到 ChatPageActivity 的相同连接?

请任何人帮助我

【问题讨论】:

    标签: android xmpp chat


    【解决方案1】:

    使用单例模式 (http://en.wikipedia.org/wiki/Singleton_pattern) 创建一个新类(在新的 .java 文件中),您可以在其中保持当前活动连接可从应用程序的任何位置访问。

    可能的解决方案:

    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;
      }
    
    }
    

    然后,在 LoginActivity 上设置连接:

    XMPPLogic.getInstance().setConnection(connection);
    

    在 ChatPage 中你会得到它:

    XMPPLogic.getInstance().getConnection().doStuff()
    

    【讨论】:

    • 如何通过我想要获得特定连接的应用程序在同一个应用程序中维护更多 XMPPConnections。我怎么能这样保养..
    • 如何识别特定的集合?通过字符串?我只是假设是这样。您可以通过更改此“private XMPPConnection connection = null;”来做到这一点到这个“私有 Map connection = new HashMap();”并更改 getter 和 setter 以获取连接名称(字符串)...您只需将连接存储在商店中。
    • 我尝试使用带有索引的 ArrayList 但没有运气。这给出了索引超出大小的异常,我会这样尝试..
    • @TiagoSimão。嗨,您能帮我实现 XMPP 连接的连接侦听器吗?在我的情况下它不起作用
    • 我们可以尝试使用 binder 来访问服务,然后访问连接吗?
    猜你喜欢
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    相关资源
    最近更新 更多