AnsweredAssumed Answered

Everytime i am trying to connect  when Internet in Case Of Internet on off Situation Getting error "SmackException Client is already logged in"

Question asked by rajgaurav on Jan 27, 2016

Everytime i am trying to connect  when Internet in Case Of Internet on off Situation Getting error "SmackException Client is already logged in", to Capture this In Event in Android Client I have Used Broadcast Receiver to connect Again , i am using Open Fire Server

 

this is My Android Code

 

public class MyXMPP {

 

   public static XMPPTCPConnection connection;

   public static MyXMPP instance;

   public static boolean isToasted;

   public static String loginUser;

   public static String passwordUser;

   public Chat Mychat;

   public static boolean connected = false;

   private boolean chat_created = false;

   public boolean loggedin = false;

  ChatService context;

  Gson gson;

  ChatManagerListenerImpl mChatManagerListener;

  MMessageListener mMessageListener;

   private String serverAddress;

   private static  Random random = new Random();

 

   static
   {

   isToasted = true;

   instance = null;

   try
   {

  Class.forName("org.jivesoftware.smack.ReconnectionManager");

 

  }

   catch (ClassNotFoundException localClassNotFoundException) {

  Log.e(MyXMPP.class.getName(), "Package Not Found !!!!!!!!!");

  }

  }

 

   private MyXMPP(ChatService paramMyService, String domain, String username, String password)

  {

   this.serverAddress = domain;

   loginUser = username;

   passwordUser = password;

   this.context = paramMyService;

  init();

  }

 

   private String getRandomNumber(){

   int i1 = random.nextInt(80 - 65) + 65;

   return ""+i1;

  }

 

   public static MyXMPP getInstance(ChatService paramMyService, String domain, String username, String password)

  {

   if (instance == null)

  {

   instance = new MyXMPP(paramMyService, domain, username, password);

  }

   return instance;

  }

 

   public static MyXMPP getInstance(){

   return instance;

  }

 

   private void initialiseConnection()

  {

  Object localObject = XMPPTCPConnectionConfiguration.builder();

  ((XMPPTCPConnectionConfiguration.Builder)localObject).setServiceName(this.serverAddress);

  ((XMPPTCPConnectionConfiguration.Builder)localObject).setHost(this.serverAddress);

  ((XMPPTCPConnectionConfiguration.Builder)localObject).setPort(5222);

  ((XMPPTCPConnectionConfiguration.Builder)localObject).setDebuggerEnabled(true);

  ((XMPPTCPConnectionConfiguration.Builder)localObject).setSecurityMode(Connectio nConfiguration.SecurityMode.disabled);

// XMPPTCPConnection.setUseStreamManagementDefault(true);
   connection = new XMPPTCPConnection(((XMPPTCPConnectionConfiguration.Builder)localObject).build()) ;

// connection.setPacketReplyTimeout(30 * 1000);
  // For Reconnection Manager
   ReconnectionManager reconnectionManager = ReconnectionManager.getInstanceFor(connection);

  reconnectionManager.setReconnectionPolicy(ReconnectionManager.ReconnectionPolic y.FIXED_DELAY);

  reconnectionManager.enableAutomaticReconnection();

 

 

  XMPPTCPConnection.setUseStreamManagementDefault(true);

// localObject = new XMPPConnectionListener();
   connection.addConnectionListener(connectionListener);

   connection.setUseStreamManagement(true);

// PingManager pingManager = PingManager.getInstanceFor(connection);
// pingManager.setPingInterval(10000);
   }

 

   public void connect()

  {

  Thread thread = new Thread(new Runnable() {

   @Override
   public void run() {

   if(connection != null) {

   try {

   connection.connect();

  Log.e(MyXMPP.class.getName(), "Connection established");

  }catch (SmackException exception){

  Log.e(MyXMPP.class.getName(), "Error SmackException " + exception.getMessage());

  }catch (XMPPException ex){

  Log.e(MyXMPP.class.getName(), "Error XMPPException "+ ex.getMessage() );

  }catch (IOException ex){

  Log.e(MyXMPP.class.getName(), "Error IOException "+ ex.getMessage() );

  }

  }else {

  Log.e(MyXMPP.class.getName(), "Connection Found NULL in Thread");

  }

  }

  });

  thread.start();

  Log.e(MyXMPP.class.getName(), "Connection Call received with User Name :" + loginUser);

 

  }

 

   public boolean isConnected(){

   return connection == null ? false : connection.isConnected();

  }

 

   public boolean isAuthenticated(){

   return connection == null ? false : connection.isAuthenticated();

  }

 

 

   public void disconnect()

  {

  MyXMPP.connection.disconnect();

  Log.e(MyXMPP.class.getName(), "User Disconnected-> :" + connection.isConnected());

  }

 

   public void init()

  {

   this.gson = new Gson();

   this.mMessageListener = new MMessageListener(this.context);

   this.mChatManagerListener = new ChatManagerListenerImpl();

  initialiseConnection();

  }

 

   public void login()

  {

   try
   {

   connection.login(loginUser, passwordUser, null);

  Log.e("LOGIN", "Yey! We're connected to the Xmpp server!");

   return;

  }

   catch (SmackException localSmackException)

  {

  Log.e(MyXMPP.class.getName(), "Login Error!!!!!!!!!!!!!" + localSmackException.getMessage());

  localSmackException.printStackTrace();

   return;

  }

   catch (Exception localException) {

  Log.e(MyXMPP.class.getName(), "Login Generic Exception !!!!!!!!!!!!!" + localException.getMessage());

   context.stopService();

  }

  }

 

   int indexCount = 0;

   public void sendMessage(final ChatMessage paramChatMessage)

  {

 

  String str = this.gson.toJson(paramChatMessage);

   if (!this.chat_created)

  {

   this.Mychat = ChatManager.getInstanceFor(connection).createChat(paramChatMessage.receiver + "@" + "6thenergy", this.mMessageListener);

 

  }

  Message localMessage = new Message();

  localMessage.setBody(str);

  localMessage.setStanzaId(paramChatMessage.msgid);

  localMessage.setType(Message.Type.chat);

   try
   {

   if (connection.isAuthenticated())

  {

   Mychat.sendMessage(localMessage);

  ChatPersistence chatdata = new ChatPersistence();

  chatdata.setSender(paramChatMessage.sender);

  chatdata.setReceiver(paramChatMessage.receiver);

   indexCount  = DBAdapter.getMaxIndexCount(chatdata);

   indexCount+=1;

   final ChatPersistence chatPersistence = new ChatPersistence(paramChatMessage.sender,paramChatMessage.receiver, paramChatMessage.body,CommonMethods.parseDate(paramChatMessage.Date),CommonMethods.parseDate(paramChatMessage.Time), indexCount,1,"Sample");

  DBAdapter.addChatData(chatPersistence);

   new Handler(Looper.getMainLooper()).post(new Runnable() {

   public void run() {

   if(ChatService.isRunning){

   context.messageReceived(chatPersistence);

  }

  Toast.makeText(context, "Sent SuccessFully Index Is " + indexCount, Toast.LENGTH_SHORT).show();

  }

  });

   return;

  }

  login();

   return;

  }

   catch (SmackException.NotConnectedException exceptionNoConnection)

  {

  Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");

   return;

  }

   catch (Exception exception){

  Log.e("xmpp.SendMessage()", "Generic Exception Received!" + exception.getMessage());

  }

  }

 

   private class ChatManagerListenerImpl

   implements ChatManagerListener

  {

   private ChatManagerListenerImpl() {}

 

   public void chatCreated(Chat paramChat, boolean paramBoolean)

  {

   if (!paramBoolean) {

  paramChat.addMessageListener(MyXMPP.this.mMessageListener);

  }

  }

  }

 

   private class MMessageListener

   implements ChatMessageListener

  {

   public MMessageListener(Context paramContext) {

 

  }

 

   private void processMessage(final ChatMessage paramChatMessage) {

  paramChatMessage.isMine = false;

   final ChatPersistence tempChat = new ChatPersistence();

  tempChat.setIsMine(0);

  tempChat.setSender(paramChatMessage.sender);

  tempChat.setReceiver(paramChatMessage.receiver);

  tempChat.setMsg(paramChatMessage.body);

// MainActivity.chatlist.add(tempChat);
   new Handler(Looper.getMainLooper()).post(new Runnable() {

   public void run() {

// if(MainActivity.chatAdapter != null)
// MainActivity.chatAdapter.notifyDataSetChanged();
   int indexCount = DBAdapter.getMaxIndexCount(tempChat);

  indexCount+=1;

   final ChatPersistence chatPersistence = new ChatPersistence(paramChatMessage.sender, paramChatMessage.receiver, paramChatMessage.body, CommonMethods.parseDate(paramChatMessage.Date), CommonMethods.parseDate(paramChatMessage.Time), indexCount, 0, "Sample");

  DBAdapter.addChatData(chatPersistence);

   if(ChatService.isRunning){

   context.messageReceived(chatPersistence);

  }

  }

  });

  }

 

   public void processMessage(final Chat paramChat,final Message paramMessage)

  {

   if ((paramMessage.getType() == Message.Type.chat) && (paramMessage.getBody() != null)) {

  Log.e("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '" + paramMessage.getBody());

   try {

  processMessage((ChatMessage) MyXMPP.this.gson.fromJson(paramMessage.getBody(), ChatMessage.class));

  }catch (JsonSyntaxException ex){

  ChatMessage chatMessage = new ChatMessage();

  chatMessage.body = paramMessage.getBody();

  chatMessage.isMine = false;

  chatMessage.sender = paramMessage.getFrom();

  chatMessage.receiver = paramMessage.getTo();

  chatMessage.Date = CommonMethods.getCurrentDate();

  chatMessage.Time = CommonMethods.getCurrentTime();

  processMessage(chatMessage);

  }

  }

  }

  }

 

 

  ConnectionListener connectionListener = new ConnectionListener() {

   @Override
   public void connected(final XMPPConnection paramXMPPConnection) {

  MyXMPP.connected = true;

   new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {

   public void run() {

  Roster roster = Roster.getInstanceFor(paramXMPPConnection);

  Collection<RosterEntry> entries = null;

   if(!roster.isLoaded()){

  entries = roster.getEntries();

   for (RosterEntry entry : entries) {

  Log.e("xmpp", "Users Count !@@@@@@@@@@@:-" + entry.getName());

  }

  }

  }

  },2000);

 

   if (!loggedin) {

  Log.e(MyXMPP.class.getName(), "Login Called From Here");

  MyXMPP.this.login();

  }

 

   new Handler(Looper.getMainLooper()).post(new Runnable()

  {

   public void run()

  {

  Toast.makeText(MyXMPP.this.context, "Connected!",Toast.LENGTH_SHORT).show();

  }

  });

 

  }

 

   @Override
   public void authenticated(XMPPConnection connection, boolean resumed) {

  Log.e("xmpp", "Authenticated!@@@@@@@@@");

  MyXMPP.this.loggedin = true;

  ChatManager.getInstanceFor(MyXMPP.connection).addChatListener(MyXMPP.this.mChatManagerListener);

  MyXMPP.this.chat_created = false;

   if (MyXMPP.isToasted) {

   new Handler(Looper.getMainLooper()).post(new Runnable()

  {

   public void run()

  {

  Toast.makeText(MyXMPP.this.context, "Authenticated!",Toast.LENGTH_SHORT).show();

  }

  });

  }

  }

 

   @Override
   public void connectionClosed() {

   if (MyXMPP.isToasted) {

   new Handler(Looper.getMainLooper()).post(new Runnable()

  {

   public void run()

  {

  Toast.makeText(MyXMPP.this.context, "ConnectionCLosed!", Toast.LENGTH_SHORT).show();

  }

  });

  }

  Log.e("xmpp", "ConnectionCLosed!");

  MyXMPP.connected = false;

  MyXMPP.this.chat_created = false;

  MyXMPP.this.loggedin = false;

  }

 

   @Override
   public void connectionClosedOnError(Exception e) {

   if (MyXMPP.isToasted) {

   new Handler(Looper.getMainLooper()).post(new Runnable()

  {

   public void run()

  {

  Toast.makeText(MyXMPP.this.context, "ConnectionClosedOn Error!!", Toast.LENGTH_SHORT).show();

  }

  });

  }

  Log.e("xmpp", "ConnectionClosedOn Error!" + e.getMessage());

  MyXMPP.connected = false;

  MyXMPP.this.chat_created = false;

  MyXMPP.this.loggedin = false;

  }

 

   @Override
   public void reconnectionSuccessful() {

   if (MyXMPP.isToasted) {

   new Handler(Looper.getMainLooper()).post(new Runnable()

  {

   public void run()

  {

  Toast.makeText(MyXMPP.this.context, "REConnected!", Toast.LENGTH_SHORT).show();

  }

  });

  }

  Log.e("xmpp", "ReconnectionSuccessful");

  MyXMPP.connected = true;

  MyXMPP.this.chat_created = false;

  MyXMPP.this.loggedin = false;

  }

 

   @Override
   public void reconnectingIn(int seconds) {

  Log.e("xmpp", "Reconnectingin " + seconds);

  MyXMPP.this.loggedin = false;

  }

 

   @Override
   public void reconnectionFailed(Exception e) {

   if (MyXMPP.isToasted) {

   new Handler(Looper.getMainLooper()).post(new Runnable()

  {

   public void run()

  {

  Toast.makeText(MyXMPP.this.context, "ReconnectionFailed!", Toast.LENGTH_LONG).show();

  }

  });

  }

  Log.e("xmpp", "ReconnectionFailed!");

  MyXMPP.connected = false;

  MyXMPP.this.chat_created = false;

  MyXMPP.this.loggedin = false;

  }

  };

 

}

Outcomes