我是新程序员。我想通过使用 xmpp 服务器实现聊天示例应用程序。在这个实现中,我使用 ConnectionConfiguration 对象创建了连接,如下所示:
ConnectionConfiguration connConfig =new ConnectionConfiguration(host, Integer.parseInt(sport), service);
我正在通过调用连接方法将 connConfig 对象传递给 XMPPConnection 类,我正在获取连接,并通过调用使用用户名和密码传递的登录方法,然后我登录到密码。要登录,我正在使用一个按钮。当我单击按钮时我正在使用 Intent 来更改 Activity 。一个我正在更改 Activity ,我想在另一个 Activity 中获得相同的连接。
我为 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 的相同连接?
请任何人帮助我
最佳答案
使用单例模式 (http://en.wikipedia.org/wiki/Singleton_pattern) 创建一个新类(在新的 .java 文件中),您可以在其中保持当前 Activity 连接可从应用程序的任何位置访问。
可能的解决方案:
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()
关于android - 如何获得从一项 Activity 到另一项 Activity 的相同 xmpp 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7565291/