I am creating an android chat application using xmpp smack library.I have create a background service to listen to incoming chats and use an application class to initialize the xmpp connection object.
The problem is the chatCreated function of chat listener is called twice therefore duplicate message is shown..
This is my application class where i have created connection
Authenticate.java
public class Authenticate extends Application {
private static final String DOMAIN = StaticVariables.chatServer;
private static final String HOST = StaticVariables.chatServer;
private static final int PORT = 5222;
static AbstractXMPPConnection connection ;
String username,password;
private boolean connected;
#Override
public void onCreate() {
super.onCreate();
}
public AbstractXMPPConnection initializeXMPPTCPConnection(String username,String password) {
Log.e("APPLICATION", "username: "+username);
Log.e("APPLICATION", "password: "+password);
Log.i("APPLCATION", "initializeXMPPTCPConnection calle:");
this.username=username;
this.password=password;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(username, password);
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=connectConnection();
Log.e("APPLICATION", "initializeXMPPTCPConnection: "+connection.isConnected());
return connection;
}
public AbstractXMPPConnection getConnection(){
return connection;
}
public AbstractXMPPConnection connectConnection()
{
AsyncTask<Void, Void, AbstractXMPPConnection> connectionThread = new AsyncTask<Void, Void, AbstractXMPPConnection>() {
#Override
protected AbstractXMPPConnection doInBackground(Void... arg0) {
// Create a connection
try {
connection.connect().login();
Log.e("Application", "doInBackground: "+connection.isConnected());
//login();
connected = true;
//sendMsg();
} catch (IOException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
return connection;
}
#Override
protected void onPostExecute(AbstractXMPPConnection connection2) {
super.onPostExecute(connection2);
// sendMsg(message.getText().toString());
Log.e("APPLICATION", "onPostExecute: "+connection2.isConnected());
connection=connection2;
}
};
try {
connection=connectionThread.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.e("Application", "connectConnection: "+connection.isConnected());
return connection;
}
public void login() {
try {
connection.login(username, password);
Log.e("APPLICATIPN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
}
This is the code through which i am calling connection instance
connection=((Authenticate)getApplication()).getConnection();
Listener function
public void listenChat(String name){
ChatManager manager = ChatManager.getInstanceFor(connection);
manager.addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(final Chat chat, boolean createdLocally) {
System.out.println("Created chat");
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(final Chat chat, final org.jivesoftware.smack.packet.Message message) {
//This is called twice
}
}
});
}
});
}
I am a beginner in android and as well in xmpp.Please tell me where i am wrong how can i resolve it
You have to fix createdLocally usage in chatCreated method.
Just add the listener if is not createdLocally like this:
public void chatCreated(Chat chat, boolean createdLocally)
{
if (!createdLocally)
{
chat.addMessageListener(new ChatMessageListener()...);
}
}
Related
I am new to Android and are trying to connect a mysql database to my android app, but I don't get it with the Async Task to work.
What is the best way to use Async Task in here.
Note: "name_db=readSQL1();
System.out.println(name_db+"###########################");" this prints
hier sollte name###########################
Here is my code:
b_login.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
name_db=readSQL1();
System.out.println(name_db+"###########################");
name_to_check=ed_name.getText().toString();
pw_temp=ed_pw.getText().toString();
try { pw_hash=hash(getSHA(ed_pw.getText().toString()));
} catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
for(int i=0;i<user_arr.size();i++) {
if (name_to_check.equals(user_arr.get(i)) && pw_hash.equals(pw_arr.get(i))) {
startActivity(new Intent(MainActivity.this, com.example.new_app.UserMain.class).putExtra("user_name",name_to_check));
} else {
Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show();
tx_counter.setVisibility(View.VISIBLE);
tx_counter.setBackgroundColor(Color.WHITE);
counter--;
tx_counter.setText(Integer.toString(counter));
if (counter==0){
b_login.setEnabled(false);
}
}
}
}
});
b_cancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
}
public static String hash(byte[] hashwert){
BigInteger number=new BigInteger(1,hashwert);
StringBuilder hexString=new StringBuilder(number.toString(16));
while (hexString.length()<32) hexString.insert(0,"0");
return hexString.toString();
}
public static byte[] getSHA(String input) throws NoSuchAlgorithmException{
MessageDigest md=MessageDigest.getInstance("SHA-256");
return md.digest(input.getBytes(StandardCharsets.UTF_8));
}
public static String readSQL1(){
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String name="hier sollte name";
try{
String url1 = "jdbc:mysql://host.de:3306/h153555_androidstudio?serverTimezone=UTC";
String user = "username"; String password = "password"; String database="user_db"; //password and username temporary
conn = DriverManager.getConnection(url1, user, password);
if (conn != null) {
stmt=conn.createStatement();
String select="SELECT NAME, PW FROM "+database;
rs=stmt.executeQuery(select);
System.out.println("read");
while(rs.next()){
name=rs.getString("NAME"); String pw=rs.getString("PW");
}
}
}catch(SQLException e){
System.out.println(e); System.out.println("read fehler");
}finally {
try { rs.close(); } catch (Exception e) { /* ignored */ }
try { stmt.close(); } catch (Exception e) { /* ignored */ }
try { conn.close(); } catch (Exception e) { /* ignored */ }
}
return name;
}
Take a look in android developers references:
https://developer.android.com/reference/android/os/AsyncTask
And you can simply use the FutureTask class
https://developer.android.com/reference/java/util/concurrent/FutureTask
You can use it this way, the Callable call function is the function that run in the task execute process.
FutureTask futureTask_1 = new FutureTask(new Callable<Integer>()
{
#Override
public Integer call() throws Exception {
return 0;
}
});
ExecutorService executor = Executors.newFixedThreadPool(1);
List<FutureTask> taskList = new ArrayList<FutureTask>();
taskList.add(futureTask_1);
executor.execute(futureTask_1);
futureTask_1.get();
I'm trying Smack 4.2 on Android and I have a problem with the IncomingListener.
I created a class MyXMPP totaly dedicated to XMPP work.
( I just have one android activity. )
In this activity, in OnCreate(), I connected to XMPP server using my class MyXMPP and I retrieved my ChatManager in my a final value to place on an IncomingChatMessageListener().
Everything works well in the first try. But when I pause my activity and relaunch it, it's like the older listener remains. So at this moment, I receive messages in double.
If I pause again my application, it's like I have 3 listeners and so on.
I precise I have no problem whith connection to my server.
Here my code :
Android activity :
public class TestMessagingActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_messaging);
MyXMPPP.getInstance().init("test", "test");
MyXMPPP.getInstance().connect();
final ChatManager chatManager = MyXMPPP.getInstance().getChatManager();
chatManager.addIncomingListener(new IncomingChatMessageListener() {
#Override
public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
final AsyncTask<Message, Void, Void> mReceiveMessage = new AsyncTask<Message, Void, Void>() {
#Override
protected Void doInBackground(Message... params) {
ChatMessage chatMessage = new ChatMessage(params[0].getBody(), false);
Log.v("TAG", "index=message arrived");
Log.v("TAG", params[0].getBody());
return null;
}
#Override
protected void onPostExecute(Void res) {
}
};
mReceiveMessage.execute(message);
}
});
}
}
MyXMPP class :
public class MyXMPPP {
private static final String DOMAIN = "test.com";
private AbstractXMPPConnection connection;
private XMPPConnectionListener connectionListener = new XMPPConnectionListener();
private ChatManager chatManager;
private Presence presence;
boolean isConnected=false;
boolean chatManagerCreated=false;
private static MyXMPPP instance =null;
public synchronized static MyXMPPP getInstance() {
if(instance==null){
instance = new MyXMPPP();
}
return instance;
}
public void init(String user, String password) {
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(user, password);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.required);
configBuilder.setKeystoreType(null);
try {
configBuilder.setXmppDomain(DOMAIN);
} catch (XmppStringprepException e) {
e.printStackTrace();
}
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
}
public void connect() {
if (isConnected == false) {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
try {
connection.connect();
connection.login();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
};
connectionThread.execute();
}
}
public AbstractXMPPConnection getConnection() {
return connection;
}
public void createChatManager()
{
if(chatManagerCreated==false)
{
chatManager=ChatManager.getInstanceFor(connection);
chatManagerCreated=true;
Log.v("TAG", "index=chat manager created");
}
}
public ChatManager getChatManager()
{
return chatManager;
}
public void sendMessage(String message, EntityBareJid jid)
{
if(chatManagerCreated==true)
{
Chat chat = chatManager.chatWith(jid);
try {
chat.send(message);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public boolean getIsConnected(){
return isConnected;
}
public class XMPPConnectionListener implements ConnectionListener{
#Override
public void connected(XMPPConnection connection) {
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
isConnected=true;
createChatManager();
presence = new Presence(Presence.Type.available, "Online", 24, Presence.Mode.available);
try {
connection.sendStanza(presence);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void connectionClosed() {
isConnected=false;
}
#Override
public void connectionClosedOnError(Exception e) {
isConnected=false;
}
#Override
public void reconnectionSuccessful() {
}
#Override
public void reconnectingIn(int seconds) {
}
#Override
public void reconnectionFailed(Exception e) {
}
}
}
Is this problem normal ?
When I put the listener to on the chatManager in the XMPP class, I don't have this problem. But I would like to do work in my activity / in my view, so having the listener here seems to be better.
I need some advice.
Thank you.
Nico.
I am using the latest Smack library 4.3.1. The XMPP connection is working fine
with WiFi but it's not working with 4G network.
Here is my code for creating a connection with XMPP.
configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(this.userName, this.password);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setServiceName(Constants.HOST);
configBuilder.setPort(Constants.PORT);
configBuilder.setHost(Constants.HOST);
configBuilder.setDebuggerEnabled(Isdebugmode);
configBuilder.setResource(PDCustomer.getResource());
configBuilder.setSendPresence(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.setPacketReplyTimeout(30000);
connection.addConnectionListener(XmppConnection.this);
connection.addAsyncStanzaListener(XmppConnection.this, null);
try {
connection.connect();
connection.login(userName, password);
} catch (IOException e) {
printlog("CONNECT IO EXCEPTION:" + e.getMessage());
} catch (SmackException e) {
printlog("CONNECT SMACK EXCEPTION:" + e.getMessage());
} catch (XMPPException e) {
printlog("CONNECT XMPP EXCEPTION:" + e.getMessage());
}
I have tested below code in 4G network
Create new class of XMPPConnection
public class XMPPConnection implements ConnectionListener, ChatManagerListener, RosterListener, ChatMessageListener, PingFailedListener {
private static final String TAG = "XMPPConnection";
public static final String HOST = "XX.XX.XXX.XX"; //Replace this value
public static final int PORT = 5222;
public static final String SERVICE = "XX.XX.XXX.XX"; //Replace this value
public static String USERNAME = ""; // Replace this value
public static String PASSWORD = ""; //Replace this value
public static String TEST_JID = "android_dummy"; // Only for testing purpose
private static XMPPConnection mInstance = new XMPPConnection();
private AbstractXMPPConnection mConnection;
private ChatManager mChatmanager;
private Chat mChat;
private Context mContext;
private String mUserName = "";
private String mPassword = "";
public XMPPConnection() {
}
public static XMPPConnection getInstance() {
return mInstance;
}
//Initialize
public void init(String userId, String pwd, Context context) throws SmackException.NotConnectedException {
Log.i("XMPP", "Initializing!");
this.mUserName = userId;
this.mPassword = pwd;
this.mContext = context;
if (userId.contains("#")) {
this.mUserName = userId.split("#")[0];
Log.i("UserId", this.mUserName);
}
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(mUserName, mPassword);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setServiceName(SERVICE);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
configBuilder.setResource("");
//configBuilder.setDebuggerEnabled(true);
mConnection = new XMPPTCPConnection(configBuilder.build());
PingManager pingManager = PingManager.getInstanceFor(mConnection);
pingManager.setPingInterval(300); // 2.5 min
pingManager.registerPingFailedListener(this);
mChatmanager.getInstanceFor(mConnection).addChatListener(this);
ReconnectionManager.getInstanceFor(mConnection).enableAutomaticReconnection();
mConnection.addConnectionListener(this);
connectConnection(context);
}
public void connectConnection(final Context context) {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
mConnection.connect();
if (mConnection != null) {
Log.i(TAG, "doInBackground: ServerStatus:Connected= " + mConnection.isConnected());
login(context);
}
} catch (IOException e) {
Log.i(TAG, "doInBackground : ServerStatus : IOException = " + e.getMessage());
} catch (SmackException e) {
Log.i(TAG, "doInBackground : ServerStatus : SmackException = " + e.getMessage());
} catch (XMPPException e) {
Log.i(TAG, "doInBackground : ServerStatus : XMPPException = " + e.getMessage());
}
return null;
}
};
connectionThread.execute();
}
public void login(Context context) {
try {
Log.i(TAG, "login: USERNAME:" + mUserName + " PASSWORD:" + mPassword);
mConnection.login(mUserName, mPassword);
if (mConnection.isAuthenticated()) {
Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
sendMessage("", TEST_JID, "", "", "", "android_dummy", "android", "android", context);
}
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
Log.i(TAG, "Login : Exception = " + e.getMessage());
}
}
public void sendMessage(String message, String to, String from, String dattingId, String deviceToken, String senderName, String senderOSName, String opponentOSName, Context context) {
this.mContext = context;
if (mConnection.isConnected() == true) {
Log.i(TAG, "sendMsg: Sending Message...");
// Assume we've created an XMPPConnection name "connection".
mChatmanager = ChatManager.getInstanceFor(mConnection);
mChat = mChatmanager.createChat("" + to, this);
// Original code
try {
Message msg = new Message();
// Set message
msg.setBody(message);
msg.setType(Message.Type.chat);
msg.setTo("" + to);
msg.setFrom("" + from);
Log.i(TAG, "Message to send : " + msg.toXML());
mChat.sendMessage(msg);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "sendMsg : Unable to send Message.");
}
}
// Disconnect Function
public void disconnectConnection() {
new Thread(new Runnable() {
#Override
public void run() {
if (mConnection != null && mConnection.isConnected())
mConnection.disconnect();
mConnection = null;
}
}).start();
}
#Override
public void processMessage(Chat chat, Message message) {
if (mConnection.isConnected() && mConnection != null) {
Log.i(TAG, "Message " + message);
}
}
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
Log.i(TAG, "chatCreated()");
chat.addMessageListener(this);
}
#Override
public void connected(org.jivesoftware.smack.XMPPConnection connection) {
Log.i(TAG, "Listener connected = " + connection.getUser());
}
#Override
public void authenticated(org.jivesoftware.smack.XMPPConnection connection, boolean resumed) {
Log.i(TAG, "Listener authenticated = " + connection.getUser());
Log.i(TAG, "Listener authenticated = resumed : " + resumed);
}
#Override
public void connectionClosed() {
Log.i(TAG, "Listener connectionClosed");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.i(TAG, "Listener connectionClosedOnError = " + e.getMessage());
}
#Override
public void reconnectionSuccessful() {
Log.i(TAG, "Listener reconnectionSuccessful");
if (mContext != null) {
sendMessage("", TEST_JID, "", "", "", "android_dummy", "android", "android", mContext);
}
}
#Override
public void reconnectingIn(int seconds) {
Log.i(TAG, "Listener reconnectingIn = " + seconds);
}
#Override
public void reconnectionFailed(Exception e) {
Log.i(TAG, "Listener reconnectionFailed = " + e.getMessage());
}
#Override
public void pingFailed() {
Log.i(TAG, "Listener pingFailed");
}
#Override
public void entriesAdded(Collection<String> addresses) {
}
#Override
public void entriesUpdated(Collection<String> addresses) {
}
#Override
public void entriesDeleted(Collection<String> addresses) {
}
#Override
public void presenceChanged(Presence presence) {
Log.i(TAG, "presenceChanged: " + presence.getClass().toString());
}
}
Now call init() method like,
// Check XMPP connection
try {
XMPPConnection.getInstance().init(USER_JABBERID, USER_JABBER_PASSWORD, HomeActivity.this);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
I used code from this tutorial https://causeyourestuck.io/2016/04/27/node-js-android-tcpip/, but got the such errors:
Cannot resolve method 'send(java.lang.String)'
Cannot resolve method 'disconnect()'
Problem in Client.java class, which I created from tutorial (link above), but I can't resolve this problem.
MainActivity.java
void doIt() {
Client socket = new Client("192.168.0.8", 1234);
socket.setClientCallback(new Client.ClientCallback () {
#Override
public void onMessage(String message) {
}
#Override
public void onConnect(Socket socket) {
socket.send("Hello World!\n");
socket.disconnect();
}
#Override
public void onDisconnect(Socket socket, String message) {
}
#Override
public void onConnectError(Socket socket, String message) {
}
});
socket.connect();
}
Client.java
public class Client {
private Socket socket;
private OutputStream socketOutput;
private BufferedReader socketInput;
private String ip;
private int port;
private ClientCallback listener=null;
public Client(String ip, int port){
this.ip=ip;
this.port=port;
}
public void connect(){
new Thread(new Runnable() {
#Override
public void run() {
socket = new Socket();
InetSocketAddress socketAddress = new InetSocketAddress(ip, port);
try {
socket.connect(socketAddress);
socketOutput = socket.getOutputStream();
socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
new ReceiveThread().start();
if(listener!=null)
listener.onConnect(socket);
} catch (IOException e) {
if(listener!=null)
listener.onConnectError(socket, e.getMessage());
}
}
}).start();
}
public void disconnect(){
try {
socket.close();
} catch (IOException e) {
if(listener!=null)
listener.onDisconnect(socket, e.getMessage());
}
}
public void send(String message){
try {
socketOutput.write(message.getBytes());
} catch (IOException e) {
if(listener!=null)
listener.onDisconnect(socket, e.getMessage());
}
}
private class ReceiveThread extends Thread implements Runnable{
public void run(){
String message;
try {
while((message = socketInput.readLine()) != null) { // each line must end with a \n to be received
if(listener!=null)
listener.onMessage(message);
}
} catch (IOException e) {
if(listener!=null)
listener.onDisconnect(socket, e.getMessage());
}
}
}
public void setClientCallback(ClientCallback listener){
this.listener=listener;
}
public void removeClientCallback(){
this.listener=null;
}
public interface ClientCallback {
void onMessage(String message);
void onConnect(Socket socket);
void onDisconnect(Socket socket, String message);
void onConnectError(Socket socket, String message);
}
}
That's because you're calling those methods on Socket (which comes from your callback) and not on your Client (which is in another scope) because they have the same name and java will use the smallest variable scope.
Change the name of your callback variable or the name of your Client variable and it should work when using the correct one :)
Ex:
void doIt() {
final Client myClient = new Client("192.168.0.8", 1234);
myClient.setClientCallback(new Client.ClientCallback () {
#Override
public void onMessage(String message) {
}
#Override
public void onConnect(Socket socket) {
myClient.send("Hello World!\n");
myClient.disconnect();
}
#Override
public void onDisconnect(Socket socket, String message) {
}
#Override
public void onConnectError(Socket socket, String message) {
}
});
myClient.connect();
}
I am working on Android Chat app based on Smack 4.1.7.
I have created my XMPP related operations on Saperate class said MyXMPP.java.
and in my app's Application class i am initializing MyXMPP class objects.
my problem is, suppose we have user 1 and user 2. if user 1 sends message to user 2 then user 2 can get message but cant reply back. means if user 2 trying to reply then user 1 can not get user 2's reply.
in short if user 1 initiates chatting then, only user 1 can send message. user 2 can not send message to user 1 same Vice versa.
my codes are as below,
MyXMPP.java
public class MyXMPP {
static Context context;
static XMPPTCPConnectionConfiguration.Builder xmppConfig;
static XMPPTCPConnection connection;
static MyXMPP myXMPP = null;
static Chat chat;
Roster roster;
ArrayList<Rosters> rosters;
static ChatManager chatManager;
static Application app;
public static synchronized MyXMPP getInstance(Context c) {
app = (Application) c.getApplicationContext();
context = c;
if (myXMPP == null) {
myXMPP = new MyXMPP();
xmppConfig = XMPPTCPConnectionConfiguration.builder();
xmppConfig.setResource(Constants.RESOURCE);
xmppConfig.setServiceName(Constants.SERVICE_NAME);
xmppConfig.setPort(Constants.PORT);
xmppConfig.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
}
return myXMPP;
}
public static synchronized AbstractXMPPConnection getConnectXMPP() {
try {
xmppConfig.setUsernameAndPassword(Constants.USERNAME, Constants.PASSWORD);
XMPPTCPConnection.setUseStreamManagementDefault(true);
connection = new XMPPTCPConnection(xmppConfig.build());
connection.setUseStreamManagement(true);
connection.connect().login();
connection.requestSmAcknowledgement();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
return connection;
}
public static ChatManager getChatManager() {
if (chatManager == null) {
chatManager = ChatManager.getInstanceFor(app.connection);
}
return chatManager;
}
public ArrayList<Rosters> getRosters() {
rosters = new ArrayList<>();
roster = Roster.getInstanceFor(app.connection);
if (!roster.isLoaded())
try {
roster.reloadAndWait();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (SmackException.NotLoggedInException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
//Get Roster Entry list
Set<RosterEntry> rosterEntries = roster.getEntries();
Debug.e("entry size", "" + rosterEntries.size());
for (final RosterEntry entry : rosterEntries) {
/*
build List<> for roster entry with roster
---or---
if it is in activity or in fragment then add both items (entry,roster) to adapter
*/
Rosters rosterItem = new Rosters();
rosterItem.entry.add(entry);
rosterItem.roster.add(roster);
rosters.add(rosterItem);
}
return rosters;
}
public void initChatManager() {
if (chatManager == null) {
chatManager = getChatManager();
}
chatManager.addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
MyXMPP.chat = chat;
if (!createdLocally) {
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
Debug.e("Chat obj", chat.toString());
if (message != null || !message.getBody().equalsIgnoreCase(null) || !message.getBody().equalsIgnoreCase("")) {
if (message.getBody() == null || message.getBody().equals(null)) {
} else {
Debug.e("Message aala", "" + message.getBody());
}
} else {
Debug.e("message null", "Message Null");
}
}
});
} else {
Debug.e("MY MSG", chat.getParticipant());
}
}
});
}
public void sendMessage(String to, String msg) {
Chat newChat = app.myXMPP.getChatManager().createChat(to, new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
System.out.println("Received message: " + message);
}
});
try {
Message message = new Message();
message.setFrom(connection.getUser());
message.setTo("xyz#myhostaddress.com");
message.setBody("My Message");
newChat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
Debug.e("send msg listener", message.getBody());
}
});
newChat.sendMessage(message);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Application app;
Button btn;
String threadId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
app.myXMPP.sendMessage("xyz#myhost.com", "hello");
}
});
//Get Application data access
app = (Application) getApplicationContext();
//Establish Connection and Login
new XMPPOperations().execute();
}
class XMPPOperations extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (app.connection == null || !app.connection.isConnected()) {
app.connection = app.myXMPP.getConnectXMPP();
Debug.e("Connection in activity", "" + app.connection.isConnected());
}
app.myXMPP.getRosters();
app.myXMPP.initChatManager();
return null;
}
}
}
Application.java
public class Application extends android.app.Application {
public MyXMPP myXMPP;
public AbstractXMPPConnection connection;
#Override
public void onCreate() {
super.onCreate();
myXMPP = MyXMPP.getInstance(this);
}
#Override
public void onTerminate() {
super.onTerminate();
Presence p = new Presence(Presence.Type.unavailable);
try {
connection.sendStanza(p);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}