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