Você está na página 1de 15

3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

WhatisXMPP?

ExtensibleMessagingandPresenceProtocol(XMPP)isanopenXMLtechnologyforrealtime
communicationasexplainedintheofficialsiteinfosection.

MainBenefitsofusingitisitsfeaturesuchasPresencetonotifyuserstateaswellas
beingextensiblethereforeallowingyoutoextenditscapibilitytosendImagesandVideotoo.Other
solutionsdonotprovidesuchadvancefeaturesandtoadduserstatessuchastyping/awayisveryhard
toimplementyetcoretoachatapp.Therefore,XMPPisagoodchoiceforchatapps.

RoadmapofTutorial

Beforewemoveontoexplainingthingsandtocode,alittlereviewofwhatthistutorialwillcoverwillbe
good.

1)HowToRunAEjabberdServerOnYourMac/Localhost

Wewillberunningaejabberdxmppserverforourchatapp.Stepstoinstallandconfigureitwillbe
given.

2)RegisteringAUserThroughTerminal

Itsgoodtogetfamiliarwiththeworkingofserverusingterminalforfutureuse.Youcanreadandexplore
moreonejabberdsite.

3)Using/RegisteringAccountOnAdium(AJabberClient)

Tobeabletochatbetweentwouser,weneedtohaveourapp(firstclient)andanotherclientforuser2.
Adiumwillactastheseconduser

4)LogInTheUserOnTheServerWithTheAndroidApp

ConnectingandLoginwiththeserverplushandlingerrorswillbeexplained.

5)SendingTo/FroMessageToTheOtherUserThroughAndroidApp.

Thispartwillhaveuscodeformessagescomingfromotheruseraswellassendingmessagefromthe
app.

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 1/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

Step1.Downloadingejabbered

Wewillbeusingejabberedserverforourapp.
Thereareseveralxmppserversavailableoutthere,Openfirebeingapopularalternative.

Goaheadanddownloadtheejabberedcommunityserverinstallerfromhere.

RuntheSetup

InstallittotheDefaultPathwhichwillbesomethinglike Applications/ejabbered/ ontheMacOS


X.

Fortheservernameyoucanuselocalhost

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 2/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

UseAdminastheadminnameand12345forthepasswordfornow

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 3/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 4/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

ejabberedwillinstallnow.Clickdoneatthefinalscreen.

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 5/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

Step2.RegisteringAUserThroughTerminal

Stepsarealsoexplainedhereforyourreferencehttps://docs.ejabberd.im/developer/installosx/.

OpenaTerminalfolderandcdintotheejabberdpath.

Forversion16.06inMacOSX.Thecommandwillbe cd/Applications/ejabberd16.06

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 6/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

Toruntheserverusethecommand. sbin/ejabberdctllive

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 7/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

Toregistertheuser>usethesyntaxregisterusernameservernamepass.
Theoneihaveused bin/ejabberdctlregisteruser1localhostpass

Step3.Using/RegisteringAccountOnAdium(AJabberClient)

SinceourserverissetupusingaXMPPbasedprotocol,wewillbeusingajabberclienttoconnecttoour
serverandcheckouthowitperforms.GoaheadanddownloadAdiumfromhttps://adium.im/.

Installitandlaunchit,closeanyaccountassitantsetupifitcomes.Nowyouwillseeascreensomething
likethis:

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 8/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

NowopenAdiumpreferencesfromthetopmenu.

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 9/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

InAccountclicktheaddbuttonatthebottomleftandselectxmppjabberaccount

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 10/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

Entertheusername@hostandthenapassikept123

AalertwillcomewiththetextRequestedURLwasnotfoundonthisserver:Clickok.Nowinthe
serverenterthehostnamei.elocalhostinourcase

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 11/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

Clickingrequestnewaccountwillnowregisterthisandyouwillhavetheadiumclientsetupforthis.

Step4.LogInTheUserOnTheServerWithTheAndroidApp

Nowwithourserversetupandadiumrunningwiththeseconduser,timetomovetoAndroidStudioto
buildthechatapp.

OpenupStudioandcreateanewbasicactivitytemplateprojectnamedXMPP.

SetupGradleforSmack

WewillbeusingSMACKforconnectingtotheserver.Itisaopensource,welldocumentedclientAPIfor
xmpp.
Belowisthegradledependecieswewillbeusing:

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 12/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

dependencies{
compilefileTree(dir:'libs',include:['*.jar'])
testCompile'junit:junit:4.12'
compile'com.android.support:appcompatv7:23.3.0'
compile"org.igniterealtime.smack:smacktcp:4.1.0"

//OptionalforXMPPTCPConnection
compile"org.igniterealtime.smack:smackandroidextensions:4.1.0"

Syncyourproject.

MainActivityCode


publicclassMainActivityextendsAppCompatActivity{

@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyLoginTasktask=newMyLoginTask();
task.execute("");
}

privateclassMyLoginTaskextendsAsyncTask<String,String,String>{
@Override
protectedStringdoInBackground(String...params){
//Createaconnectiontothejabber.orgserver.
XMPPTCPConnectionConfigurationconfig=XMPPTCPConnectionConfiguration.builder
.setUsernameAndPassword("user1","123")
.setHost("10.0.2.2")
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setServiceName("localhost")
.setPort(5222)
.setDebuggerEnabled(true)//toviewwhat'shappeningindetail
.build();

AbstractXMPPConnectionconn1=newXMPPTCPConnection(config);
try{
conn1.connect();
if(conn1.isConnected()){
Log.w("app","conndone");
}

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 13/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

conn1.login();

if(conn1.isAuthenticated()){
Log.w("app","Authdone");
}
}
catch(Exceptione){
Log.w("app",e.toString());
}

return"";
}

@Override
protectedvoidonPostExecute(Stringresult){
}

}
}

WecreateaAsyncTaskclass MyLoginTask todothenetworkrequestandauthenticationinbackground


threadandcallitfromour onCreate() method.

Inthe doInBackground wecreateourconfigobject,fieldswesetareusernameAndPasswordof


user1wecreatedusingterminal.
Thehostsetis10.0.2.2insteadoflocalhostsinceandroidemulatorreferslocalhosttoitselfsoweneed
touse10.0.2.2forouremulatortoconnecttoMacslocalhost.

Securityisdisabledandtheservicenameforourconnectionpurposewespecifyaslocalhost.Nextwe
setthedefaultxmppportof5222and setDebuggerEnabled(true) sothatwereceiveproperlogsof
anyconnectionfailure/success.

Withthisconfigwecreateourconnectionobjectandtrytoconnecttoourserverandsubsequentlylogin.
Calling conn1.isAuthenticated() willreturnuswhethertheuserhasbeenauthenticatedwiththe
server.
Alloftheconnectionandauthcallarewrappedinatrycatchsothatwecancatchanyfailureandtake
properaction.

Runtheappandifeverythinghasbeenfollowedcorrectly,youwillseetheauthDonelogintheconsole.

Step5.RecieveMessageFromTheOtherUserThroughAndroidApp.

Addthefollowingcodeinthe isAuthenticated conditionoftheasynctask.

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 14/15
3/9/2017 ChatApplicationUsingXmppSmackApiAndroidTutorial

if(conn1.isAuthenticated())
{
Log.w("app","Authdone");
ChatManagerchatManager=ChatManager.getInstanceFor(conn1);
chatManager.addChatListener(
newChatManagerListener(){
@Override
publicvoidchatCreated(Chatchat,booleancreatedLocally)
{
chat.addMessageListener(newChatMessageListener()
{
@Override
publicvoidprocessMessage(Chatchat,Messagemessage){
System.out.println("Receivedmessage:"
+(message!=null?message.getBody():"NULL"));
}
});

Log.w("app",chat.toString());
}
});
}

Hereweadda chatListener toourChatManagerclassprovidedbySmackforthecurrentxmpp


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

Nowruntheappandsendmessagetouser1fromAdiumclient.Youshallseeinthelogsproper
messagebeingreceived.

Conclusion

Thankyouforreadingthisfar.Foranyquestionsyouarewelcometoaskinourchatroom.

http://shubhank101.github.io/iOSAndroidChaosOverFlow/2016/10/ChatApplicationUsingXMPPSmackAPIAndroidTutorial 15/15

Você também pode gostar