Question

I am working on a Chat Application using XMPP with asmack. At startup Activity I want to make XMPP connection then use it in the different activities. But I have no idea how to do this. I searched a lot about it but couldn't find any desired solution. Please guide me.

Was it helpful?

Solution

You could make the Connection member static and choose a access level modifier keyword that allows other Activities access that member.

But, you usually don't want to have the Connection be handled within an Activity, but within an class that extends Service. There are a bunch of open source apps out there that use aSmack, have a look at their source.

OTHER TIPS

you can use this class to set the connection and get it anywhere in other 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;
  }

}

and set the connection like this..

XMPPLogic.getInstance().setConnection(connection);

and get connection like this..

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

you can use singleton design pattern or make a utility class and define xmpp connection as static and then you can use it in any activity.

for singleton do like this :

public class MyConnection{
private static MyConnection con;
private MyConnection(){

        //ToDo here

}
public static MyConnection getInstance()
{
    if (con == null)
   {
      MyConnection= new MyConnection();
   }
   return con;
   }

}

then in any activity you can access that object by typing MyConnection.getInstance();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top