0% found this document useful (1 vote)
173 views15 pages

XMPP Smack API Android Chat Tutorial

This document provides an overview and roadmap for a tutorial on building a chat application using the XMPP protocol and Smack API for Android. It discusses: 1) What XMPP is and its main benefits for building chat apps 2) The steps that will be covered in the tutorial, including running an Ejabberd XMPP server, registering users, using the Adium client, and logging in and sending messages from an Android app using Smack. 3) High-level instructions for some of the initial steps, such as downloading and configuring Ejabberd, registering a test user, and setting up an account in the Adium client.

Uploaded by

Ashish John
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
173 views15 pages

XMPP Smack API Android Chat Tutorial

This document provides an overview and roadmap for a tutorial on building a chat application using the XMPP protocol and Smack API for Android. It discusses: 1) What XMPP is and its main benefits for building chat apps 2) The steps that will be covered in the tutorial, including running an Ejabberd XMPP server, registering users, using the Adium client, and logging in and sending messages from an Android app using Smack. 3) High-level instructions for some of the initial steps, such as downloading and configuring Ejabberd, registering a test user, and setting up an account in the Adium client.

Uploaded by

Ashish John
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

WhatisXMPP?

ExtensibleMessagingandPresenceProtocol(XMPP)isanopenXMLtechnologyforrealtime
communicationasexplainedintheofficialsiteinfosection.

MainBenefitsofusingitisitsfeaturesuchasPresencetonotifyuserstateaswellas
[Link]
solutionsdonotprovidesuchadvancefeaturesandtoadduserstatessuchastyping/awayisveryhard
[Link],XMPPisagoodchoiceforchatapps.

RoadmapofTutorial

Beforewemoveontoexplainingthingsandtocode,alittlereviewofwhatthistutorialwillcoverwillbe
good.

1)HowToRunAEjabberdServerOnYourMac/Localhost

[Link]
given.

2)RegisteringAUserThroughTerminal

[Link]
moreonejabberdsite.

3)Using/RegisteringAccountOnAdium(AJabberClient)

Tobeabletochatbetweentwouser,weneedtohaveourapp(firstclient)andanotherclientforuser2.
Adiumwillactastheseconduser

4)LogInTheUserOnTheServerWithTheAndroidApp

ConnectingandLoginwiththeserverplushandlingerrorswillbeexplained.

5)SendingTo/FroMessageToTheOtherUserThroughAndroidApp.

Thispartwillhaveuscodeformessagescomingfromotheruseraswellassendingmessagefromthe
app.

[Link] 1/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

[Link]

Wewillbeusingejabberedserverforourapp.
Thereareseveralxmppserversavailableoutthere,Openfirebeingapopularalternative.

Goaheadanddownloadtheejabberedcommunityserverinstallerfromhere.

RuntheSetup

InstallittotheDefaultPathwhichwillbesomethinglike Applications/ejabbered/ ontheMacOS


X.

Fortheservernameyoucanuselocalhost

[Link] 2/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

UseAdminastheadminnameand12345forthepasswordfornow

[Link] 3/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

[Link] 4/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

[Link].

[Link] 5/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

[Link]

Stepsarealsoexplainedhereforyourreference[Link]

OpenaTerminalfolderandcdintotheejabberdpath.

[Link] cd/Applications/ejabberd16.06

[Link] 6/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

Toruntheserverusethecommand. sbin/ejabberdctllive

[Link] 7/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

Toregistertheuser>usethesyntaxregisterusernameservernamepass.
Theoneihaveused bin/ejabberdctlregisteruser1localhostpass

[Link]/RegisteringAccountOnAdium(AJabberClient)

SinceourserverissetupusingaXMPPbasedprotocol,wewillbeusingajabberclienttoconnecttoour
[Link]://[Link]/.

Installitandlaunchit,[Link]
likethis:

[Link] 8/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

NowopenAdiumpreferencesfromthetopmenu.

[Link] 9/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

InAccountclicktheaddbuttonatthebottomleftandselectxmppjabberaccount

[Link] 10/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

Entertheusername@hostandthenapassikept123

AalertwillcomewiththetextRequestedURLwasnotfoundonthisserver:[Link]
[Link]

[Link] 11/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

Clickingrequestnewaccountwillnowregisterthisandyouwillhavetheadiumclientsetupforthis.

[Link]

Nowwithourserversetupandadiumrunningwiththeseconduser,timetomovetoAndroidStudioto
buildthechatapp.

OpenupStudioandcreateanewbasicactivitytemplateprojectnamedXMPP.

SetupGradleforSmack

[Link],welldocumentedclientAPIfor
xmpp.
Belowisthegradledependecieswewillbeusing:

[Link] 12/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

dependencies{
compilefileTree(dir:'libs',include:['*.jar'])
testCompile'junit:junit:4.12'
compile'[Link]:appcompatv7:23.3.0'
compile"[Link]:smacktcp:4.1.0"

//OptionalforXMPPTCPConnection
compile"[Link]:smackandroidextensions:4.1.0"

Syncyourproject.

MainActivityCode


publicclassMainActivityextendsAppCompatActivity{

@Override
protectedvoidonCreate(BundlesavedInstanceState){
[Link](savedInstanceState);
setContentView([Link].activity_main);
MyLoginTasktask=newMyLoginTask();
[Link]("");
}

privateclassMyLoginTaskextendsAsyncTask<String,String,String>{
@Override
protectedStringdoInBackground(String...params){
//[Link].
XMPPTCPConnectionConfigurationconfig=[Link]
.setUsernameAndPassword("user1","123")
.setHost("[Link]")
.setSecurityMode([Link])
.setServiceName("localhost")
.setPort(5222)
.setDebuggerEnabled(true)//toviewwhat'shappeningindetail
.build();

AbstractXMPPConnectionconn1=newXMPPTCPConnection(config);
try{
[Link]();
if([Link]()){
Log.w("app","conndone");
}

[Link] 13/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

[Link]();

if([Link]()){
Log.w("app","Authdone");
}
}
catch(Exceptione){
Log.w("app",[Link]());
}

return"";
}

@Override
protectedvoidonPostExecute(Stringresult){
}

}
}

WecreateaAsyncTaskclass MyLoginTask todothenetworkrequestandauthenticationinbackground


threadandcallitfromour onCreate() method.

Inthe doInBackground wecreateourconfigobject,fieldswesetareusernameAndPasswordof


user1wecreatedusingterminal.
Thehostsetis10.0.2.2insteadoflocalhostsinceandroidemulatorreferslocalhosttoitselfsoweneed
touse10.0.2.2forouremulatortoconnecttoMacslocalhost.

[Link]
setthedefaultxmppportof5222and setDebuggerEnabled(true) sothatwereceiveproperlogsof
anyconnectionfailure/success.

Withthisconfigwecreateourconnectionobjectandtrytoconnecttoourserverandsubsequentlylogin.
Calling [Link]() willreturnuswhethertheuserhasbeenauthenticatedwiththe
server.
Alloftheconnectionandauthcallarewrappedinatrycatchsothatwecancatchanyfailureandtake
properaction.

Runtheappandifeverythinghasbeenfollowedcorrectly,youwillseetheauthDonelogintheconsole.

[Link].

Addthefollowingcodeinthe isAuthenticated conditionoftheasynctask.

[Link] 14/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

if([Link]())
{
Log.w("app","Authdone");
ChatManagerchatManager=[Link](conn1);
[Link](
newChatManagerListener(){
@Override
publicvoidchatCreated(Chatchat,booleancreatedLocally)
{
[Link](newChatMessageListener()
{
@Override
publicvoidprocessMessage(Chatchat,Messagemessage){
[Link]("Receivedmessage:"
+(message!=null?[Link]():"NULL"));
}
});

Log.w("app",[Link]());
}
});
}

Hereweadda chatListener toourChatManagerclassprovidedbySmackforthecurrentxmpp


connection.
Weoverridethechatcreatedmethodwhichwillbecalledforeachconversationwithdifferentusers.
Inthe chatCreated methodweadda ChatMessageListener whichprovidesuswiththemessage
bodyofthechatandmanyotherattributessuchasusername,timestampetc.

[Link]
messagebeingreceived.

Conclusion

[Link].

[Link] 15/15

You might also like