Smack API Android Documentation and Examples

Hi Everyone,

I hope you all doing well, Actually i need a favour from you. I want to know that if there any Example Application built for android using the Latest Smack API.

I want to create a chat client for my xmpp server and for that i want to use SMACK API but i can not find detailed Examples and documentation for the API so that i can use the code in my app.

Please give me reference .

Thank You

My friend, please, if you found the answer or if you turn able to make a app using smack let me know, because i have the same difficulty.

Hello . Come me Skype i speek or write you. Write me in PM and i write you my Skype.

The code i writed in Eclipse Luna.

Eclipse Luna:

static AbstractXMPPConnection conn2;

static XMPPTCPConnectionConfiguration config;

config = XMPPTCPConnectionConfiguration.builder()

//Базовыйе настройки

.setUsernameAndPassword("SenderID@gcm.googleapis.com", “Server_Key”)

.setServiceName(“gcm.googleapis.com”)

.setHost(“gcm.googleapis.com”)

.setPort(5235)

.setDebuggerEnabled(true)

//.setSendPresence(false)

.setSocketFactory(SSLSocketFactory.getDefault())

//.setSecurityMode(XMPPTCPConnectionConfiguration.SecurityMode.ifpossible)

.build();

conn2 = new XMPPTCPConnection(config);

conn2.setPacketReplyTimeout(10000);

conn2.connect();

//==========

try {

conn2.login();

} catch (SmackException | IOException | XMPPException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

//Детектор соединения

System.out.println(conn2.isAuthenticated());

}

//==========

AndroidStudio:

View.OnClickListener button1X = new View.OnClickListener() {

@Override
public void onClick(View v) {

Bundle data = new Bundle();

data.putString(“message-x”,editText1.getText().toString());

data.putString(“action-x”, editText2.getText().toString());

//task.execute(data);
AcTack(data);

}

};

button.setOnClickListener(button1X);

private void AcTack(Bundle data){

new AsyncTask<Bundle, Integer, String>() {

@Override
protected String doInBackground(Bundle… damara) {

//==============================
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(getApplicationContext());

AtomicInteger ccsMsgId = new AtomicInteger();

String id = Integer.toString(ccsMsgId.incrementAndGet());

try {

gcm.send(SENDER_ID + "@gcm.googleapis.com", id, Long.parseLong(“10000”), damara[0]);

// gcm.send(SENDER_ID + "@gcm.googleapis.com", id, dataBundle);
Log.i(“111”, "Отправляем ");

} catch (IOException e) {

e.printStackTrace();

}

//==============================
return null;

}

@Override
protected void onPostExecute(String msg) {

}

}.execute(data, null, null);

}

Thanks Yrii,

Code for the android studio is not using SMACK XMPP connection or XMPP TCP Connection class. And thanks for your response here i get my connection work in android studio:

  1. Add SMACK API to android project by adding dependencies in build.gradle for the app.

compile ‘org.igniterealtime.smack:smack-android:4.1.4’
// Optional for XMPPTCPConnection
compile ‘org.igniterealtime.smack:smack-tcp:4.1.4’
// Optional for XMPP-IM (RFC 6121) support (Roster, Threaded Chats)
compile ‘org.igniterealtime.smack:smack-im:4.1.4’
// Optional for XMPP extensions support
compile ‘org.igniterealtime.smack:smack-extensions:4.1.4’

  1. Here is my MYXMPP CLASS code which i am using to connect

We can use the following class by making an object of this class, and also i am creating github repository for the Android Smack API Example Application which is located at axcl/SMACK-API-Android-Demo · GitHub

import android.os.AsyncTask;

import android.os.Handler;

import android.os.Looper;

import android.util.Log;

import org.jivesoftware.smack.AbstractXMPPConnection;

import org.jivesoftware.smack.ConnectionConfiguration;

import org.jivesoftware.smack.ConnectionListener;

import org.jivesoftware.smack.SmackException;

import org.jivesoftware.smack.XMPPConnection;

import org.jivesoftware.smack.XMPPException;

import org.jivesoftware.smack.chat.Chat;

import org.jivesoftware.smack.chat.ChatManager;

import org.jivesoftware.smack.tcp.XMPPTCPConnection;

import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;

import java.io.IOException;

/**

  • Created by Ankit on 10/3/2015.
    */
    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(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.connect();

login();

connected = true;

} catch (IOException e) {

} catch (SmackException e) {

} 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

}

});

}

}

}

Hello Ankit,

Have you ever tried to use some installable xmpp server like ejabberd for example?

I ask because i´m trying to use the ejabberd with xmpp and its not working.

Hello Gustavo,

Yep i have tried this on my own ejabberd host also. Please provide me the error logs and settings you are using.

Hello again,

I tried to use your example (on git) and i put my domain and host configurations. I have these errors when i try to connect.

10-21 19:45:12.228 16480-16501/com.demoapp.messenger W/System.err﹕ org.jivesoftware.smack.sasl.SASLErrorException: SASLError using DIGEST-MD5: not-authorized

10-21 19:45:12.228 16480-16501/com.demoapp.messenger W/System.err﹕ at org.jivesoftware.smack.SASLAuthentication.authenticationFailed(SASLAuthenticati on.java:365)

10-21 19:45:12.228 16480-16501/com.demoapp.messenger W/System.err﹕ at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPC onnection.java:1040)

10-21 19:45:12.228 16480-16501/com.demoapp.messenger W/System.err﹕ at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$300(XMPPTCPCon nection.java:944)

10-21 19:45:12.228 16480-16501/com.demoapp.messenger W/System.err﹕ at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnecti on.java:959)

10-21 19:45:12.228 16480-16501/com.demoapp.messenger W/System.err﹕ at java.lang.Thread.run(Thread.java:818)

10-21 19:45:49.580 16480-16487/com.demoapp.messenger W/art﹕ Suspending all threads took: 10.769ms

The server is running on my localhost (10.0.2.2)

Can you check again if you have this line,

configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)

in your code.

Yes i have.

My Code is exactly the same of your gitl

It is not my code but I wrote similar code on Android which works fine.
If code is same, then it seems server is unable to disable security
policy while login due to some configuration settings ? Could
you please check there. BTW, what server are you using ?

Rigth now i´m using open fire, with your code i not tried with ejabberd yet. And you? What server?

This setting is (mostly) unrelated to the SASL error.

@Aejaz I think that the

“configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)” disables only the TLS encryption and client will always uses SASL Authentication. If you are just testing then you can use SASL PLAIN.

P.S:- For real world applications you should definitely use a more encrypted method and use SASL PLAIN only if you understand the risks.

Hai ankit, thanks for providing nice code example for xmpp connection. you code is working fine. i successfully established the connection and logged in. but while using chatmanger i am getting this error ‘incompatitabletype:AbstractXMPPConnection cannot be converted to XMPPConnection’. how to fix this error…?

here is my coding .

XMPPTCPConnection connection = new XMPPTCPConnection(“XXXX”,“XXXX”,“XXXX”);

Then run

11-07 15:51:36.694: E/AndroidRuntime(11069): java.lang.NoClassDefFoundError: org.jivesoftware.smack.tcp.XMPPTCPConnection;

Can u help me ?

Hi,

Use XMPPConnection class instead of XMPPTCPConnection class and try make connection shown below my code is working fine.

ConnectionConfiguration config = new ConnectionConfiguration(“your-domain-name”, 5222);

XMPPConnection connection = new XMPPConnection(config);

which version of smack api you are using?

hai hiren, your code was correct but it was deprecated so suggest you to use this

private XMPPTCPConnection mConnection;

private static String HOST = “hostname”;

private static int PORT = 5222;

private static String SERVICE = “servicename”;

XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();

        builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);

builder.setServiceName(SERVICE);

builder.setHost(HOST);

builder.setPort(PORT);

        builder.setUsernameAndPassword("karthick@jabb.im","superdoom");

builder.setResource(“Smack”);

mConnection = new XMPPTCPConnection(builder.build());

and i suggest you to use JAVA version below 1.8

hi @karthick,

Thanks for your suggestion.

could you define whats the main diffrance between xmppconnection and xmpptcpconnection?

i am currently using java version 8 if i’ve changed xmppconntion to xmpptcpconnection is it cause any problem due to java version?

Why? Using Smack 4.1 with Java 8 is perfectly fine.