Add custum tags in Message Using Smack 4.1.+

hi,

In this post we are going to discuss about  how to add custom tags in message using smack

if we send a message using default method it only send the recipient,sender info along with the message only

To view the Logs in detail add the following line for debugging.

SmackConfiguration.DEBUG=true;

so if we send a message the following log you can see

<r xmlns='urn:xmpp:sm:3'/>
<a xmlns='urn:xmpp:sm:3' h='5'/>
<message from='xxxx@localhost/Smack' to='xxxxx@localhost' 
xml:lang='en' id='ywF9d-33' type='chat'>
<body>hiiii</body>
<thread>e199d18d-bPed-400d-aa97-98888888767517</thread>
</message><r xmlns='urn:xmpp:sm:3'/>

So what if you need to add the Timestamp with your message?

we use DefaultExtensionElement 

Default implementation of the ExtensionElement interface. 
Unless a ExtensionElementProvider is registered with ProviderManager, 
instances of this class will be returned when getting stanza(/packet) 
extensions.

This class provides a very simple representation of an XML sub-document. Each element is a key in a Map with its CDATA being the value.

SENDING CUSTOM ATTRIBUTE

Let get started to add custom Tag

DefaultExtensionElement extTime = new DefaultExtensionElement(
        "time", "urn:xmpp:time");

so we are creating a tag time with xml attribute urn:xmpp:time

Ok now let set value to tag  time

String messageTimeStamp = String.valueOf(System.currentTimeMillis());
extTime.setValue("time", messageTimeStamp);

setting the extension to the message body

Message msg = new Message();
msg.addExtension(extTime);

The complete method is as below for sending custom message

//To sent message
public void sendLocaTimeMessage() throws SmackException.NotConnectedException {

Message msg = new Message();
msg.setBody(YOUR MESSAGE);

//Getting current timestamp in string format
String messageTimeStamp = String.valueOf(System.currentTimeMillis());

//Creating default packet extension with name as ‘timestamp’ and urn as ‘urn:xmpp:timestamp’

DefaultExtensionElement extTime = new DefaultExtensionElement(
“time”, “urn:xmpp:time”);

//Setting value in extension
extTime.setValue(“time”, messageTimeStamp);

//Add extension to message tag
msg.addExtension(extTime);
Chat newChat = chatManager.createChat(RECIPIENT);

//Send message
newChat.sendMessage(msg);

}

Continue reading “Add custum tags in Message Using Smack 4.1.+”

Advertisements

Getting the Buddylist in Smack 4.1.+

Hi in this topic we are discussing about getting  buddy list using smack

before  going to coding part we need to know what is Roaster

Represents a user’s roster, which is the collection of users a person receives presence updates for. Roster items are categorized into groups for easier management.

initialize roaster after connection

Roster.getInstanceFor(connection);

 

Call the following methods to get the buddy list

public List<RosterEntry> getBuddies() throws SmackException.NotLoggedInException, InterruptedException, SmackException.NotConnectedException {
    Roster roster = Roster.getInstanceFor(connection);
    if (!roster.isLoaded())
        roster.reloadAndWait();
    Collection<RosterEntry> entries = roster.getEntries();
    List<RosterEntry> roasterInfo = new ArrayList<RosterEntry>();
 for (RosterEntry entry : entries) {
  roasterInfo.add(entry);
 Log.d(TAG,"Here: " + entry.toString());
 Log.d(TAG,"User: " + entry.getUser());//get userinfo
 Log.d(TAG,"User Name:"+entry.getName());//get username
 Log.d(TAG,"User Status: "+entry.getStatus())//get status of user
 }
 return roasterInfo;
}

In the next post its about Delivery Manager smack.

Handling connection break issue in Smack 4.1.+

Hi in this post i would like to share how to make the connection stable in smack, so the main issue when comes to mobile development is that there should not be any network stability guaranteed in mobile if our network provider is not good. Also there are various reason make connection fail like deep sleep mode, if we don’t handle those problems we cant receive any messages because our app will not reconnect when the connection get stable again.So there are some methods implemented in smack to handle these portions.

1)PingManager

Implements the XMPP Ping as defined by XEP-0199. The XMPP Ping protocol allows one entity to ping any other entity by simply sending a ping to the appropriate JID. PingManger also periodically sends XMPP pings to the server to avoid NAT timeouts and to test the connection status.

The default server ping interval is 30 minutes and can be modified with setDefaultPingInterval(int) and setPingInterval(int). (more)

Uses

Register the pingManager after the connection

PingManager.getInstanceFor(connection)

You can set ping interval with your choice usually its 30 minutes  by default, but u can override that by adding

setPingInterval(YOUR TIME)
PingManager.getInstanceFor(connection).setPingInterval(600);//in secounds
in Example 600 sec is 5 minutes

implement PingFailedListener which contain method when ping is failed with server

// Ping Failed listener.

/**
 * Called when the server ping fails.
 */
@Override
public void pingFailed() {
// Do operation to handle if ping fail like force reconnect etc
}

2)ServerPingWithAlarmManager

Send automatic server pings with the help of AlarmManager.

Smack’s PingManager uses a ScheduledThreadPoolExecutor to schedule the automatic server pings, but on Android, those scheduled pings are not reliable. This is because the Android device may go into deep sleep where the system will not continue to run this causes

the system time to not move forward, which means that the time spent in deep sleep is not counted towards the scheduled delay time
the scheduled Runnable is not run while the system is in deep sleep.

That is the reason Android comes with an API to schedule those tasks: AlarmManager. Which this class uses to determine every 30 minutes if a server ping is necessary. The interval of 30 minutes is the ideal trade-off between reliability and low resource (battery) consumption.

In order to use this class you need to call onCreate(Context) once, for example in the onCreate() method of your Service holding the XMPPConnection. And to avoid leaking any resources, you should call onDestroy() when you no longer need any of its functionality. (more)

ServerPingWithAlarmManager.getInstanceFor(connection).isEnabled();

3)ReconnectionManager

Handles the automatic reconnection process. Every time a connection is dropped without the application explicitly closing it, the manager automatically tries to reconnect to the server.

There are two possible reconnection policies: ReconnectionManager.ReconnectionPolicy.RANDOM_INCREASING_DELAY – The reconnection mechanism will try to reconnect periodically:

1)For the first minute it will attempt to connect once every ten seconds.
2)For the next five minutes it will attempt to connect once a minute.
3)If that fails it will indefinitely try to connect once every five minutes.

ReconnectionManager.ReconnectionPolicy.FIXED_DELAY – The reconnection mechanism will try to reconnect after a fixed delay independently from the number of reconnection attempts already performed. (more)

ReconnectionManager.getInstanceFor(connection);

To enable Auto reconnect add the following lines

ReconnectionManager.getInstanceFor(connection).enableAutomaticReconnection();

 

When reconnection start smack will notify when it reconnect again in the following method

/**
 * The connection will retry to reconnect in the specified number of seconds.
 * <p>
 * Note: This method is only called if {@link ReconnectionManager#isAutomaticReconnectEnabled()} returns true, i.e.
 * only when the reconnection manager is enabled for the connection.
 * </p>
 *
 * @param seconds remaining seconds before attempting a reconnection.
 */
@Override
public void reconnectingIn(int seconds) {

}

 

Onces reconnection is success full you will get notify in the

/**
 * The connection has reconnected successfully to the server. Connections will
 * reconnect to the server when the previous socket connection was abruptly closed.
 */
@Override
public void reconnectionSuccessful() {

}

 

if reconnection fails the following methods will called

/**
 * An attempt to connect to the server has failed. The connection will keep trying reconnecting to the server in a
 * moment.
 * <p>
 * Note: This method is only called if {@link ReconnectionManager#isAutomaticReconnectEnabled()} returns true, i.e.
 * only when the reconnection manager is enabled for the connection.
 * </p>
 *
 * @param e the exception that caused the reconnection to fail.
 */
@Override
public void reconnectionFailed(Exception e) {

}

reconnectingIn(int seconds)

reconnectionSuccessful()

reconnectionFailed(Exception e)

comes under the implemented interface ConnectionListener which discussed in the previous topic

in next post i will post how to get the roasters(your buddy list from xmpp using smack)

 

 

 

Send messages over Xmpp using Smack 4.1.+

Hi all in the previous post we discuss about smack and login using smack just go through the category Xmpp Android. In this post we are going to handle how to transfer messages using xmpp android.

SEND A MESSAGE USING SMACK

Declare the Chat Manager which  keeps track of references to all current chats (more)

private ChatManager chatManager;


initialize it after the connection is begin establisher lets take
XMPPTCPConnection connection is your connection variable.
initialize the ChatManager as below
chatManager = ChatManager.getInstanceFor(connection);

 

Let first add the method to send chat

public void sendMessage(String to, Message newMessage) {
if(chatManager!=null) {
Chat newChat = chatManager.createChat(to);

try {
if (connection.isConnected() && connection.isAuthenticated()) {

newChat.sendMessage(newMessage);
}
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
else
{
Log.d(TAG,”chatmanager is null”);
}
}

 

the above method is just a example when we send a message we embed the body of your message and also add recipient(to whom you send the message) in the chatManager and initialize in a Chat object. So as we say we add message to the Message class.

Setting message is as follows

Message newMessage = new Message();
newMessage.setBody("YOUR MESSAGE HERE");

 

and set the address of the recipient in Chat newChat = chatManager.createChat(to); Here to is the address of your recipient, in message body we can add custom tags will post that in the up coming posts so this how we send messages using smack 4.1+.

Receive incoming message in Smack

Above we discuss how to send a message using smack now we will discuss how to handle the incoming messages

first we need to implement

ChatManagerListener (Event fired when a new chat is created.)
it overrides a method 
void chatCreated(Chat chat, boolean createdLocally)
This is were we handles the incoming messages 



Continue reading “Send messages over Xmpp using Smack 4.1.+”

Login to xmpp server using smack

Hi, this article is  about setting up a XMPP chat Login Session using latest smack library in android to know more about smack go to my previous post Make A Chat App Using Xmpp using Smack 4.1.+.

ext {
    smackVersion = '4.1.+' //replace + with the latest version
}

//Add dependency files for smack

dependencies {
   
    compile "org.igniterealtime.smack:smack-android:$smackVersion"
    compile "org.igniterealtime.smack:smack-tcp:$smackVersion"
    compile "org.igniterealtime.smack:smack-core:$smackVersion"
    compile "org.igniterealtime.smack:smack-extensions:$smackVersion"
compile "org.igniterealtime.smack:smack-android-extensions:$smackVersion"
}

Now lets go to the main coding part

Set the port,host and other main server info of you xmpp server

public static final String HOST = "Your Host Address";
public static final int PORT = 5222;
public static final int CONNECT_TIME_OUT = 80000;
public static final String RESOURCE = "SMACK";/any name as your 
feasibility
public static final String SERVICENAME="YOUR SERVICENAME"//any name so 
your feasibility

Let start the login process before that implement the following interface in your class

ConnectionListener

it overrides the following methods

/**
 * Notification that the connection has been successfully connected to the remote endpoint (e.g. the XMPP server).
 * <p>
 * Note that the connection is likely not yet authenticated and therefore only limited operations like registering
 * an account may be possible.
 * </p>
 *
 * @param connection the XMPPConnection which successfully connected to its endpoint.
 */
@Override
public void connected(XMPPConnection connection) {

}

/**
 * Notification that the connection has been authenticated.
 *
 * @param connection the XMPPConnection which successfully authenticated.
 * @param resumed    true if a previous XMPP session's stream was resumed.
 */
@Override
public void authenticated(XMPPConnection connection, boolean resumed) {

}

/**
 * Notification that the connection was closed normally.
 */
@Override
public void connectionClosed() {

}

/**
 * Notification that the connection was closed due to an exception. When
 * abruptly disconnected it is possible for the connection to try reconnecting
 * to the server.
 *
 * @param e the exception.
 */
@Override
public void connectionClosedOnError(Exception e) {

}

/**
 * The connection has reconnected successfully to the server. Connections will
 * reconnect to the server when the previous socket connection was abruptly closed.
 */
@Override
public void reconnectionSuccessful() {

}

/**
 * The connection will retry to reconnect in the specified number of seconds.
 * <p>
 * Note: This method is only called if {@link ReconnectionManager#isAutomaticReconnectEnabled()} returns true, i.e.
 * only when the reconnection manager is enabled for the connection.
 * </p>
 *
 * @param seconds remaining seconds before attempting a reconnection.
 */
@Override
public void reconnectingIn(int seconds) {

}

/**
 * An attempt to connect to the server has failed. The connection will keep trying reconnecting to the server in a
 * moment.
 * <p>
 * Note: This method is only called if {@link ReconnectionManager#isAutomaticReconnectEnabled()} returns true, i.e.
 * only when the reconnection manager is enabled for the connection.
 * </p>
 *
 * @param e the exception that caused the reconnection to fail.
 */
@Override
public void reconnectionFailed(Exception e) {

}

 

Continue reading “Login to xmpp server using smack”

Make A Chat App Using Xmpp using Smack 4.1.+

Hi, this article is a about setting up a XMPP chat using latest smack library in android.

Before starting the coding part lets start with smack library

SMACK

A highly modular and portable open source XMPP client library written in Java for JVMs and Android http://www.igniterealtime.org/projects/smack/. A pure Java library, it can be embedded into your applications to create anything from a full XMPP client to simple XMPP integrations such as sending notification messages and presence-enabling devices. Smack and XMPP allows you to easily exchange data, in various ways e.g. fire-and-forget, publish-subscribe, between human and non-human endpoints.

You can find more about About smack github, the latest smack is made much compatible with android.Old release was meant for web based type chat system it was not handling the conditions like deep sleep mode,timeout in mobile also connectivity issue etc, all but is handling in the latest version, to find more about smack deeply just go though this documentation

 

 

Some of the xmpp Servers you can work with

1)ejabberd

products_ejabberd_saas

LINK: https://www.ejabberd.im/

2)OPEN FIRE

logo-openfire

 

LINK: http://www.igniterealtime.org/projects/openfire/

 

Some of the Useful Android Projects

 

2)Conversations

Link: https://github.com/siacs/Conversations

3)flicker

Link: https://github.com/Xlopec/flicker

4)MovesLikeJabber

Link: https://github.com/jezer07/MovesLikeJabber