xmpp: ConnectionClosedOn Error! Parser got END_DOCUMENT event - android

I'm trying too login to the android app that i have created whose authentication will be done using the username and password registered in ejabberd. The connection is successfully established but i'm not abe to login. It gives an error namely -
"ConnectionClosedOn Error! Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element"
The log is:
04-15 19:27:45.052 31421-31421/com.synergy.allie.ecm D/calling xmpp connect: started
04-15 19:27:45.052 31421-31749/com.synergy.allie.ecm D/Connect() Function: =>connecting....
04-15 19:27:45.072 31421-31421/com.synergy.allie.ecm D/LoginActivity: onServiceConnected
04-15 19:27:45.102 31421-31751/com.synergy.allie.ecm I/System.out: 07:27:45 PM SENT (0): http://etherx.jabber.org/streams' version='1.0' xml:lang='en'>
04-15 19:27:45.102 31421-31752/com.synergy.allie.ecm I/System.out: 07:27:45 PM RECV (0): http://etherx.jabber.org/streams' id='284868730' from='allen' version='1.0' xml:lang='en'>
04-15 19:27:45.102 31421-31752/com.synergy.allie.ecm I/System.out: 07:27:45 PM RECV (0): http://jabber.org/protocol/caps' hash='sha-1' node='http://www.process-one.net/en/ejabberd/' ver='SLr01mk3X636tk4sDXYXPXsNNcE='/>http://jabber.org/features/iq-register'/>PLAINDIGEST-MD5SCRAM-SHA-1
04-15 19:27:45.142 31421-31749/com.synergy.allie.ecm D/xmpp: Connected!
04-15 19:28:45.102 31421-31752/com.synergy.allie.ecm W/AbstractXMPPConnection: Connection closed with error
org.jivesoftware.smack.SmackException: Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1148)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$200(XMPPTCPConnection.java:937)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:952)
at java.lang.Thread.run(Thread.java:856)
04-15 19:28:45.112 31421-31752/com.synergy.allie.ecm D/xmpp: ConnectionClosedOn Error! Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element
public class MyXMPP
{
public static boolean connected = false;
public boolean loggedin = false;
public static boolean isconnecting = false;
public static boolean isToasted = true;
private boolean chat_created = false;
private String serverAddress;
public static XMPPTCPConnection connection;
public static String loginUser;
public static String passwordUser;
Gson gson;
MyService context;
public static MyXMPP instance = null;
public static boolean instanceCreated = false;
public org.jivesoftware.smack.chat.Chat Mychat;
ChatManagerListenerImpl mChatManagerListener;
MMessageListener mMessageListener;
Boolean logon;
public MyXMPP(MyService context, String serverAdress, String logiUser,
String passwordser) {
this.serverAddress = serverAdress;
this.loginUser = logiUser;
this.passwordUser = passwordser;
this.context = context;
init();
}
public static MyXMPP getInstance(MyService context, String server,
String user, String pass) {
if (instance == null) {
instance = new MyXMPP(context, server, user, pass);
instanceCreated = true;
}
return instance;
}
String text = "";
String mMessage = "", mReceiver = "";
static {
try {
Class.forName("org.jivesoftware.smack.ReconnectionManager");
} catch (ClassNotFoundException ex) {
// problem loading reconnection manager
}
}
public void init() {
gson = new Gson();
mMessageListener = new MMessageListener(context);
mChatManagerListener = new ChatManagerListenerImpl();
initialiseConnection();
}
private void initialiseConnection() {
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(serverAddress);
config.setHost("***.***.***.***");
config.setPort(5222);
config.setDebuggerEnabled(true);
XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
connection = new XMPPTCPConnection(config.build());
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
connection.addConnectionListener(connectionListener);
}
public void disconnect() {
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
}
}).start();
}
public void connect(final String caller) {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected synchronized Boolean doInBackground(Void... arg0) {
if (connection.isConnected())
return false;
isconnecting = true;
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, caller + "Trying to establish a connection!", Toast.LENGTH_LONG).show();
}
});
Log.d("Connect() Function", caller + "=>connecting....");
try {
connection.connect();
DeliveryReceiptManager dm = DeliveryReceiptManager
.getInstanceFor(connection);
dm.setAutoReceiptMode(AutoReceiptMode.always);
dm.addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(final String fromid,
final String toid, final String msgid,
final Stanza packet) {
}
});
connected = true;
} catch (IOException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "(" + caller + ")" + "IOException: ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("(" + caller + ")", "IOException: " + e.getMessage());
} catch (SmackException e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "(" + caller + ")" + "SMACKException: ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("(" + caller + ")", "SMACKException: " + e.getMessage());
} catch (XMPPException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "(" + caller + ")" + "XMPPException: ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("connect(" + caller + ")",
"XMPPException: " + e.getMessage());
}
return isconnecting = false;
}
};
connectionThread.execute();
}
public void login()
{
try
{
connection.login(loginUser, passwordUser);
Log.i("LOGIN", "Praise Jesus! We're connected to the Xmpp server!");
logon=true;
}
catch (XMPPException | SmackException | IOException e)
{
logon=false;
e.printStackTrace();
}
catch (Exception e)
{
logon=false;
}
}
private class ChatManagerListenerImpl implements ChatManagerListener {
#Override
public void chatCreated(final org.jivesoftware.smack.chat.Chat chat,
final boolean createdLocally) {
if (!createdLocally)
chat.addMessageListener(mMessageListener);
}
}
public void sendMessage(ChatMessage chatMessage) {
String body = gson.toJson(chatMessage);
if (!chat_created) {
Mychat = ChatManager.getInstanceFor(connection).createChat(chatMessage.receiver
+ "#" + context.getString(R.string.server),
mMessageListener);
chat_created = true;
}
final Message message = new Message();
message.setBody(body);
message.setStanzaId(chatMessage.msgid);
message.setType(Message.Type.chat);
try {
if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
} else {
login();
}
} catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
} catch (Exception e) {
Log.e("xmpp.SendMessage()", "msg Not sent!" + e.getMessage());
}
}
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
login();
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "ConnectionCLosed!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "ConnectionClosedOn Error!!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ConnectionClosedOn Error! "+arg0.getMessage());
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "ReconnectionFailed!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "REConnected!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
ChatManager.getInstanceFor(connection).addChatListener(
mChatManagerListener);
chat_created = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "Connected!",
Toast.LENGTH_SHORT).show();
}
});
}
}
private class MMessageListener implements ChatMessageListener {
public MMessageListener(Context contxt) {
}
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat,
final Message message) {
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
+ message);
if (message.getType() == Message.Type.chat
&& message.getBody() != null) {
final ChatMessage chatMessage = gson.fromJson(
message.getBody(), ChatMessage.class);
processMessage(chatMessage);
}
}
private void processMessage(final ChatMessage chatMessage) {
chatMessage.isMine = false;
Chats.chatlist.add(chatMessage);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Chats.chatAdapter.notifyDataSetChanged();
}
});
}
}
}

try this code
public void initConnection(String user, String pass) throws XMPPException {
// TODO Auto-generated method stub
String SERVER_HOST = "192.168.1.199";
int SERVER_PORT = 5222;
String SERVICE_NAME = "Allen";
try {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
XMPPTCPConnectionConfiguration.Builder connConfig = XMPPTCPConnectionConfiguration
.builder();
connConfig
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
connConfig.setUsernameAndPassword(user, pass);
connConfig.setServiceName(SERVICE_NAME);
connConfig.setHost(SERVER_HOST);
connConfig.setPort(SERVER_PORT).setCompressionEnabled(false);
connConfig.setDebuggerEnabled(true);
connConfig.setConnectTimeout(25000);
XMPPTCPConnectionConfiguration configuration = connConfig.build();
// XMPPTCPConnection.setUseStreamManagementDefault(true);
// XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
// XMPPTCPConnection.setReplyToUnknownIqDefault(true);
connection = new XMPPTCPConnection(configuration);
connection.setUseStreamManagement(true);
connection.setUseStreamManagementResumption(true);
connection.setReplyToUnknownIq(true);
connection.setPacketReplyTimeout(25000);
ReconnectionManager manager = ReconnectionManager.getInstanceFor(connection);
manager.setFixedDelay(15);
ReconnectionManager.setDefaultReconnectionPolicy(ReconnectionManager.ReconnectionPolicy.FIXED_DELAY);
manager.enableAutomaticReconnection();
try {
connection.connect();
connection.login();
//logIn();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}

Related

Application not able to connect to local xmpp server

I am using this code for connecting my android app to XMPP server i.e Openfire Server with Smack API
public class MyXMPP {
private static final String DOMAIN = "localhost";
private static final String HOST = "192.168.1.2";
private static final int PORT = 9090;
private String userName ="";
private String passWord = "";
AbstractXMPPConnection connection ;
ChatManager chatmanager ;
Chat newChat;
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
private boolean connected;
private boolean isToasted;
private boolean chat_created;
private boolean loggedin;
Context c;
//Initialize
public void init(Context context,String userId,String pwd ) {
Log.i("XMPP", "Initializing!");
this.userName = userId;
this.passWord = pwd;
this.c=context;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName(DOMAIN);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
//configBuilder.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
}
// Disconnect Function
public void disconnectConnection(){
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
}
}).start();
}
public void connectConnection()
{
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
//connection.setPacketReplyTimeout(30000);
connection.connect();
login();
connected = true;
} catch (IOException e) {
}
catch (SmackException e)
{
Log.v("errror",e.getMessage());
} catch (XMPPException e) {
}
return null;
}
};
connectionThread.execute();
}
public void sendMsg() {
if (connection.isConnected()== true) {
// Assume we've created an XMPPConnection name "connection"._
chatmanager = ChatManager.getInstanceFor(connection);
newChat = chatmanager.createChat("concurer#nimbuzz.com");
try {
newChat.sendMessage("Howdy!");
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
public void login() {
try {
connection.login(userName, passWord);
Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
// Toast.makeText(c,"Login successfully",Toast.LENGTH_LONG).show();
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
//Connection Listener to check connection state
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
login();
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ConnectionClosedOn Error!"+arg0);
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
chat_created = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
}
}
}
but getting an exception i.e "No response received within reply timeout. A timeout was 10000ms (~10s). Used filter: No filter used or filter was 'null'.".
If am I missing something in my code, please let me know.

Trying to connect xmpp server by smack

I am using this code for connecting my android app to xmpp server i.e openfire Server with Smack api
public class MyXMPP {
private static final String DOMAIN = "nimbuzz.com";
private static final String HOST = "o.nimbuzz.com";
private static final int PORT = 5222;
private String userName ="";
private String passWord = "";
AbstractXMPPConnection connection ;
ChatManager chatmanager ;
Chat newChat;
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
private boolean connected;
private boolean isToasted;
private boolean chat_created;
private boolean loggedin;
//Initialize
public void init(String userId,String pwd ) {
Log.i("XMPP", "Initializing!");
this.userName = userId;
this.passWord = pwd;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(userName, passWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName("localhost");
configBuilder.setHost("192.168.1.2");
configBuilder.setPort(5222);
//configBuilder.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
}
// Disconnect Function
public void disconnectConnection(){
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
}
}).start();
}
public void connectConnection()
{
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
connection.connect();
login();
connected = true;
} catch (IOException e) {
}
catch (SmackException e)
{
Log.v("errror",e.getMessage());
} catch (XMPPException e) {
}
return null;
}
};
connectionThread.execute();
}
public void sendMsg() {
if (connection.isConnected()== true) {
// Assume we've created an XMPPConnection name "connection"._
chatmanager = ChatManager.getInstanceFor(connection);
newChat = chatmanager.createChat("concurer#nimbuzz.com");
try {
newChat.sendMessage("Howdy!");
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
public void login() {
try {
connection.login(userName, passWord);
//Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
//Connection Listener to check connection state
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
login();
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ConnectionClosedOn Error!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
chat_created = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
}
}
}
but getting an exception i.e "The following addresses failed: '192.168.1.2:9090' failed because java.net.SocketTimeoutException: failed to connect to /192.168.1.2 (port 9090) after 30000ms".If i am missing something in my code please let me know.

How to Implement Xmpp chat android

I want to imaplement xmpp connection in my application i refered lot of tutorials in google,but i cnnot get clear idea.
please some one help me out this problem,give suggetion how to implemnt xmpp connection.
thank you.
first You Have to add build.gradle
compile "org.igniterealtime.smack:smack-android:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-tcp:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-im:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-extensions:4.1.0-rc1"
then create LocalBinder class
public class LocalBinder<S> extends Binder {
private final WeakReference<S> mService;
public LocalBinder(final S service) {
mService = new WeakReference<S>(service);
}
public S getService() {
return mService.get();
}
}
Then Create service class
public class XmppService extends Service {
public static MyXMPP xmpp;
private String ServiceName = "", HostAddress = "";
private String USERNAME = "";
private String PASSWORD = "";
private SessionManager sessionManager;
#Override
public IBinder onBind(final Intent intent) {
return new LocalBinder<XmppService>(this);
}
#Override
public boolean onUnbind(final Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onCreate() {
sessionManager = new SessionManager(XmppService.this);
ServiceName = Your Service Name ;
HostAddress = Your Host Address;
USERNAME = your xmpp server user name;
PASSWORD = Your xmpp server pwd;
xmpp = MyXMPP.getInstance(XmppService.this, ServiceName, HostAddress, USERNAME, PASSWORD);
xmpp.connect("onCreate");
}
#Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
MyXMPP.instance=null;
MyXMPP.instanceCreated=false;
xmpp.connection.disconnect();
System.out.println("--------------Xmpp Service Stopped-----------");
}
}
create xmpp class
public class MyXMPP {
public static boolean connected = false;
public boolean loggedin = false;
public static boolean isconnecting = false;
public static boolean isToasted = true;
private boolean chat_created = false;
private boolean server_chat_created = false;
private String serviceName = "", hostAddress = "";
public static XMPPTCPConnection connection;
public static String loginUser;
public static String passwordUser;
XmppService context;
public static MyXMPP instance = null;
public static boolean instanceCreated = false;
private static ChatHandler chatHandler;
public MyXMPP(XmppService context, String mServiceName, String mHostAddress, String loginUser, String passwordUser) {
this.serviceName = mServiceName;
this.hostAddress = mHostAddress;
this.loginUser = loginUser;
this.passwordUser = passwordUser;
this.context = context;
init();
}
public static MyXMPP getInstance(XmppService context, String mServiceName, String mHostAddress, String user, String pass) {
if (instance == null) {
instance = new MyXMPP(context, mServiceName, mHostAddress, user, pass);
instanceCreated = true;
}
return instance;
}
public org.jivesoftware.smack.chat.Chat Mychat ,MyServerchat;
ChatManagerListenerImpl mChatManagerListener;
MMessageListener mMessageListener;
String text = "";
String mMessage = "", mReceiver = "";
static {
try {
Class.forName("org.jivesoftware.smack.ReconnectionManager");
} catch (ClassNotFoundException ex) {
// problem loading reconnection manager
}
}
public void init() {
mMessageListener = new MMessageListener(context);
mChatManagerListener = new ChatManagerListenerImpl();
initialiseConnection();
}
private void initialiseConnection() {
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(serviceName);
config.setHost(hostAddress);
config.setDebuggerEnabled(true);
config.setConnectTimeout(50000);
XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
connection = new XMPPTCPConnection(config.build());
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
connection.addConnectionListener(connectionListener);
}
public void disconnect() {
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
}
}).start();
}
public void connect(final String caller) {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected synchronized Boolean doInBackground(Void... arg0) {
if (connection.isConnected())
return false;
isconnecting = true;
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context,
caller + "=>connecting....",
Toast.LENGTH_LONG).show();*/
}
});
Log.d("Connect() Function", caller + "=>connecting....");
try {
connection.connect();
ReconnectionManager reconnectionManager =
ReconnectionManager.getInstanceFor(connection);
reconnectionManager.setEnabledPerDefault(false);
reconnectionManager.enableAutomaticReconnection();
/*PingManager pingManager =
PingManager.getInstanceFor(connection);
pingManager.setPingInterval(300);*/
DeliveryReceiptManager dm = DeliveryReceiptManager
.getInstanceFor(connection);
dm.setAutoReceiptMode(AutoReceiptMode.always);
dm.addReceiptReceivedListener(new ReceiptReceivedListener()
{
#Override
public void onReceiptReceived(final String fromid, final String toid, final String msgid,final Stanza packet) {
}
});
connected = true;
} catch (IOException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context,"(" + caller + ")"+ "IOException: ", Toast.LENGTH_SHORT).show();*/
}
});
Log.e("(" + caller + ")", "IOException: " + e.getMessage());
} catch (SmackException e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context, "(" + caller + ")" + "SMACKException: ", Toast.LENGTH_SHORT).show();*/
}
});
Log.e("(" + caller + ")",
"SMACKException: " + e.getMessage());
} catch (XMPPException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context,"(" + caller + ")"+ "XMPPException: ",Toast.LENGTH_SHORT).show();*/
}
});
Log.e("connect(" + caller + ")","XMPPException: " + e.getMessage());
}
return isconnecting = false;
}
};
connectionThread.execute();
}
public void login() {
try {
System.out.println("----login------USERNAME------------" + loginUser);
System.out.println("----login------PASSWORD------------" + passwordUser);
connection.login(loginUser, passwordUser);
Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
// connect("");
} catch (Exception e) {
}
}
private class ChatManagerListenerImpl implements ChatManagerListener {
#Override
public void chatCreated(final org.jivesoftware.smack.chat.Chat chat,final boolean createdLocally) {
if (!createdLocally)
chat.addMessageListener(mMessageListener);
}
}
public int sendMessage(String senderID, String mMessage) {
if (!chat_created) {
Mychat = ChatManager.getInstanceFor(connection).createChat(senderID, mMessageListener);
chat_created = true;
}
final Message message = new Message();
message.setBody(mMessage);
message.setStanzaId(String.format("%02d", new Random().nextInt(1000)));
message.setType(Message.Type.chat);
try {
if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
return 1;
} else {
login();
return 0;
}
} catch (SmackException.NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
return 0;
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
return 0;
}
/* try {
if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
} else {
login();
}
} catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
}*/
}
public int sendMessageServer(String senderID, String mMessage) {
if (!server_chat_created) {
MyServerchat =
ChatManager.getInstanceFor(connection).createChat(senderID, mMessageListener);
server_chat_created = true;
}
final Message message = new Message();
message.setBody(mMessage);
message.setStanzaId(String.format("%02d", new Random().nextInt(1000)));
message.setType(Message.Type.chat);
try {
if (connection.isAuthenticated()) {
MyServerchat.sendMessage(message);
return 1;
} else {
login();
return 0;
}
} catch (SmackException.NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
return 0;
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
return 0;
}
/* try {
if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
} else {
login();
}
} catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
}*/
}
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
login();
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
/*Toast.makeText(context, "ConnectionCLosed!",
Toast.LENGTH_SHORT).show();*/
}
});
Log.d("xmpp", "ConnectionCLosed!");
System.out.println("-------------ConnectionCLosed!----------------");
instance = null;
connected = false;
chat_created = false;
server_chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context, "ConnectionClosedOn Error!!",
Toast.LENGTH_SHORT).show();*/
}
});
Log.d("xmpp", "ConnectionClosedOn Error!");
connected = false;
instance = null;
chat_created = false;
server_chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
System.out.println("----------prem Reconnectingin----------------" + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context, "ReconnectionFailed!",Toast.LENGTH_SHORT).show();*/
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
instance = null;
chat_created = false;
server_chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
/*Toast.makeText(context, "REConnected!",Toast.LENGTH_SHORT).show();*/
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
server_chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
ChatManager.getInstanceFor(connection).addChatListener(mChatManagerListener);
chat_created = false;
server_chat_created = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
/*Toast.makeText(context, "Connected!",Toast.LENGTH_SHORT).show();*/
}
});
}
}
private class MMessageListener implements ChatMessageListener {
public MMessageListener(Context contxt) {
}
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat,final Message message)
{
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"+ message);
if (message.getType() == Message.Type.chat && message.getBody() != null)
{
System.out.println("-----------xmpp message-------------" + message.getBody());
try
{
if (chatHandler == null) {
chatHandler = new ChatHandler(context);
}
chatHandler.onHandleChatMessage(message);
}
catch (Exception e) {
}
}
}
}
}
Next Handle the Received Data from xmpp Class
public class ChatHandler {
private Context context;
private IntentService service;
private GEODBHelper myDBHelper;
private SessionManager session;
public ChatHandler(Context context, IntentService service) {
this.context = context;
this.service = service;
session = new SessionManager(context);
myDBHelper = new GEODBHelper(context);
}
public ChatHandler(Context context) {
this.context = context;
session = new SessionManager(context);
myDBHelper = new GEODBHelper(context);
}
public void onHandleChatMessage(Message message) {
try {
String data = URLDecoder.decode(message.getBody(), "UTF-8");
JSONObject messageObject = new JSONObject(data);
}
catch (Exception e) {
}
}
add to manifest
<service
android:name="com.app.xmpp.XmppService"
android:enabled="true" />
Start xmpp service
startService(new Intent(myclass.this, XmppService.class));
stop xmpp service
stopService(new Intent(getApplicationContext(), XmppService.class));
You can integrate Quickblox API it has multiple features like User Management, Chat, Group Chat, Video & Audio Calling.
Quickblox
Try this example https://github.com/blikoon/Rooster
It worked for me. I did my own messenger using this source
Goog luck

Android Chat app XMPP

I have created an android chat application using XMPP server (openfire) and smack lib. When open my application i get connect =>connecting than a Oncreat SMACK exception appears. Which means that i can't establish a connexion with the server my code looks right but i cant figure out where is the probleme
here is the code
public class MyXMPP {
public static ArrayList<HashMap<String, String>> usersList=new ArrayList<HashMap<String, String>>();
public static boolean connected = false;
public boolean loggedin = false;
public static boolean isconnecting = false;
public static boolean isToasted = true;
private boolean chat_created = false;
private String serverAddress;
public static XMPPTCPConnection connection;
public static String loginUser;
public static String passwordUser;
Gson gson;
MyService context;
public static MyXMPP instance = null;
public static boolean instanceCreated = false;
public MyXMPP(MyService context, String serverAdress, String logiUser,
String passwordser) {
this.serverAddress = serverAdress;
this.loginUser = logiUser;
this.passwordUser = passwordser;
this.context = context;
init();
}
public static MyXMPP getInstance(MyService context,String server,
String user,String pass) {
if (instance == null) {
instance = new MyXMPP(context,server,user,pass);
instanceCreated = true;
}
return instance;
}
public org.jivesoftware.smack.chat.Chat Mychat;
ChatManagerListenerImpl mChatManagerListener;
MMessageListener mMessageListener;
String text = "";
String mMessage = "", mReceiver = "";
static {
try {
Class.forName("org.jivesoftware.smack.ReconnectionManager");
} catch (ClassNotFoundException ex) {
// problem loading reconnection manager
}
}
public void init() {
gson = new Gson();
mMessageListener = new MMessageListener(context);
mChatManagerListener = new ChatManagerListenerImpl();
initialiseConnection();
}
private void initialiseConnection() {
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName("farah-pc");
config.setHost("farah-pc");
config.setPort(5222);
config.setDebuggerEnabled(true);
XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
connection = new XMPPTCPConnection(config.build());
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
connection.addConnectionListener(connectionListener);
}
public void connect(final String caller) {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected synchronized Boolean doInBackground(Void... arg0) {
if (connection.isConnected())
return false;
isconnecting = true;
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, caller + "=>connecting....", Toast.LENGTH_LONG).show();
}
});
Log.d("Connect() Function", caller + "=>connecting....");
try {
connection.connect();
DeliveryReceiptManager dm = DeliveryReceiptManager
.getInstanceFor(connection);
dm.setAutoReceiptMode(AutoReceiptMode.always);
dm.addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(final String fromid, final String toid, final String msgid, final Stanza packet) {
}
});
Toast.makeText( context,"cava", Toast.LENGTH_SHORT).show();
connected = true;
} catch (IOException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
Toast.makeText( context,"(" + caller + ")" + "IOException: ", Toast.LENGTH_SHORT).show();
}
});
Log.e("(" + caller + ")", "IOException: " + e.getMessage());
} catch (SmackException e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "(" + caller + ")" + "SMACKException: ", Toast.LENGTH_SHORT).show();
}
});
Log.e("(" + caller + ")","SMACKException: " + e.getMessage());
} catch (XMPPException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
Toast.makeText( context,"(" + caller + ")" + "XMPPException: ", Toast.LENGTH_SHORT).show();
}
});
Log.e("connect(" + caller + ")", "XMPPException: " + e.getMessage());
}
return isconnecting = false;
}
};
connectionThread.execute();
}
public void login() {
try {
connection.login(loginUser,passwordUser);
Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
// SmackException.ConnectionException.getFailedAddresses() ;
//HostAddress.getException();
Toast.makeText( context,"alaaach", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
private class ChatManagerListenerImpl implements ChatManagerListener {
#Override
public void chatCreated(final org.jivesoftware.smack.chat.Chat chat,
final boolean createdLocally) {
if (!createdLocally)
chat.addMessageListener(mMessageListener);
}
}
public void sendMessage(ChatMessage chatMessage) {
if (!chat_created) {
Mychat = ChatManager.getInstanceFor(connection).createChat(
chatMessage.receiver + "#"
+ context.getString(R.string.server),
mMessageListener);
chat_created = true;
}
final Message message = new Message();
message.setBody(chatMessage.getBody());
message.setType(Message.Type.normal);
try {
//if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
//} else {
login();
//}
} catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
Toast.makeText( context,"not sending", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
login();
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "ConnectionCLosed!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "ConnectionClosedOn Error!!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ConnectionClosedOn Error!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "ReconnectionFailed!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "REConnected!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
ChatManager.getInstanceFor(connection).addChatListener(
mChatManagerListener);
chat_created = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "Connected!",
Toast.LENGTH_SHORT).show();
}
});
}
}
private class MMessageListener implements ChatMessageListener {
public MMessageListener(Context contxt) {
}
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat,
final Message message) {
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
+ message);
System.out.println("Body-----"+message.getBody());
if (message.getType() == Message.Type.chat
&& message.getBody() != null) {
final ChatMessage chatMessage = new ChatMessage();
chatMessage.setBody(message.getBody());
processMessage(chatMessage);
}
}
private void processMessage(final ChatMessage chatMessage) {
chatMessage.isMine = false;
Chats.chatlist.add(chatMessage);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Chats.chatAdapter.notifyDataSetChanged();
}
});
}
}
}
//connect to server
private class MyOpenfireLoginTask extends AsyncTask<String, String, String> {
private Context mContext;
String username, password;
ProgressDialog dialog;
public MyOpenfireLoginTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(mContext);
dialog.setMessage(getResources().getString(R.string.loading_txt));
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
username = params[0];
password = params[1];
Log.e("Login using ", username + " , " + password);
Config.config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(username, password)
.setHost(Config.openfire_host_server_IP)
.setResource(Config.openfire_host_server_RESOURCE)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setServiceName(Config.openfire_host_server_SERVICE)
.setPort(Config.openfire_host_server_CHAT_PORT)
.setDebuggerEnabled(true)
.build();
Config.conn1 = new XMPPTCPConnection(Config.config);
Config.conn1.setPacketReplyTimeout(5000);
try {
Config.conn1.connect();
if (Config.conn1.isConnected()) {
Log.w("app", "conn done");
}
Config.conn1.login();
if (Config.conn1.isAuthenticated()) {
Log.w("app", "Auth done");
} else {
Log.e("User Not Authenticated", "Needs to Update Password");
}
} catch (Exception e) {
Log.w("app", e.toString());
}
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (Config.conn1.isAuthenticated()) {
setUserPresence(0);
//store data in session
sharedPreferenceManager.setUsername(username);
sharedPreferenceManager.setUserPsw(password);
if (UserListActivity.mActivity != null) {
UserListActivity.mActivity.finish();
}
Intent intent = new Intent(mContext, HomeActivity.class);
mContext.startActivity(intent);
if (LoginActivity.mActivity != null) {
LoginActivity.mActivity.finish();
}
if (SignupActivity.mActivity != null) {
SignupActivity.mActivity.finish();
}
finish();
} else {
Log.e(TAG, "username password wrong");
CommonUtils.commonToast(mContext, mContext.getResources().getString(R.string.invalid_uname_psw));
// CommonUtils.commonToast(mContext,mContext.getResources().getString(R.string.loading_txt));
}
}
}
// check connection is available or not !if not redirect to login screen.
public boolean isUserConnectedToServer(Activity mActivity) {
if (Config.conn1 != null && Config.conn1.isConnected()) {
Log.e(TAG, "----->Connected");
setUserPresence(0);
return true;
} else {
Log.e(TAG, "----->Not connected");
setUserPresence(5);
if (LoginActivity.mActivity != null) {
LoginActivity.mActivity.finish();
}
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent);
mActivity.finish();
return false;
}
}
//disconnect user from server
public void logoutUser(Activity mActivity) {
if (Config.conn1 != null && Config.conn1.isConnected()) {
Log.e(TAG, "-----isConnected------Logout");
setUserPresence(5);
Config.conn1.disconnect();
} else {
Log.e(TAG, "-----disconnect-------Not connected");
}
sharedPreferenceManager.clearData();
//stop background service
stopBackgroundService(mActivity);
if (LoginActivity.mActivity != null) {
LoginActivity.mActivity.finish();
}
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent);
mActivity.finish();
}

ReconnectionManager is not working correctly

I am using smack library to implement chat solution in android. It is making connection with openfire perfectly but reconnection is not working at all.
I have a lost a connection on a device, on connection receive it does not reconnect or call any callbacks of reconnect. Please suggest how we can reconnect to openfire using ReconnectManager.
private boolean openConnection(String account, String password) {
try {
if (null == xmppConnection || !xmppConnection.isAuthenticated()) {
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setHost(Constants.XMPP_SERVER_DOMAIN);
config.setServiceName(Constants.XMPP_SERVER_DOMAIN);
config.setPort(Constants.XMPP_SERVER_PORT);
config.setUsernameAndPassword(account, password);
//config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setCompressionEnabled(true);
config.setDebuggerEnabled(true);
TLSUtils.acceptAllCertificates(config);
xmppConnection = new XMPPTCPConnection(config.build());
xmppConnection.setPacketReplyTimeout(10000);
ReconnectionManager.getInstanceFor(xmppConnection).enableAutomaticReconnection();
connectionListener = new XmppConnectionListener();
packetListener = new XmppPacketListener();
xmppConnection.addAsyncPacketListener(packetListener, new PacketFilter() {
#Override
public boolean accept(Stanza packet) {
return true;
}
});
xmppConnection.addConnectionListener(connectionListener);
xmppConnection.connect().login();
return true;
}
} catch (XMPPException xe) {
xe.printStackTrace();
xmppConnection = null;
} catch (IOException io) {
io.printStackTrace();
xmppConnection = null;
} catch (SmackException se) {
se.printStackTrace();
xmppConnection = null;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
xmppConnection = null;
} catch (KeyManagementException e) {
e.printStackTrace();
xmppConnection = null;
}
return false;
}
XmppConnectionListener.java
public class XmppConnectionListener implements ConnectionListener {
private static final String TAG = "XmppConnectionListener";
#Override
public void reconnectionSuccessful() {
Log.d(TAG, "reconnectionSuccessful()");
}
#Override
public void reconnectionFailed(Exception arg0) {
Log.d(TAG, "reconnectionFailed()");
}
#Override
public void reconnectingIn(int arg0) {
Log.d(TAG, "reconnectingIn()");
}
#Override
public void connectionClosedOnError(Exception arg0) {
Log.d(TAG, "connectionClosedOnError()");
}
#Override
public void connected(XMPPConnection connection) {
Log.d(TAG, "connected()");
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
Log.d(TAG, "authenticated()");
}
#Override
public void connectionClosed() {
Log.d(TAG, "connectionClosed()");
}
}

Categories

Resources