Escolar Documentos
Profissional Documentos
Cultura Documentos
CrearunpluginparaAndroidenPhoneGap
EntraenAdictosatravsde
Email
Contrasea
Registrarme
Olvidmicontrasea
Entrar
Inicio
Quinessomos
Formacin
Comparadordesalarios
Nuestroslibros
Ms
AdOptions
AdsbySmartSaver
RubnAguileraDazHeredero
Consultortecnolgicodedesarrollodeproyectosinformticos.
Catlogodeservicios
Autentia
IngenieroenInformtica,especialidadenIngenieradelSoftware
PuedesencontrarmeenAutentia:Ofrecemosserviciosdesoporteadesarrollo,
factorayformacin
SomosexpertosenJava/J2EE
Vertodoslostutorialesdelautor
Fechadepublicacindeltutorial:20140326
Tutorialvisitado7.478vecesDescargarenPDF
CrearunpluginparaAndroidenPhoneGap
0.ndicedecontenidos.
1.Entorno
2.Introduccin
3.Vamosallo
4.Conclusiones
1.Entorno
Estetutorialestescritousandoelsiguienteentorno:
Hardware:PorttilMacBookPro17"(2,6GhzIntelCorei7,8GBDDR3)
SistemaOperativo:MacOSXSnowLeopard10.6.4
ApacheCordova3.4.00.1.0
2.Introduccin
Sguenosatravs
de:
ltimasNoticias
Antesdeseguirconestetutorialseaconsejahabercompletadoesteotroquenosmuestracomoempezaradarlos
primerospasosyesteotroquenosenseacomoutilizarlospluginenPhoneGap/Cordova.
AdemssitodavatehacesunloentrequeesPhoneGapyqueesApacheCordovaterecomiendoleerestnoticiaal
respecto.
Bienloquevamosaverenestetutorialescmocrearunpluginquepodamosreutilizarencualquierdenuestros
desarrolloconPhoneGap/Cordova.LospluginssonlamejorformadeextenderfuncionalidadenPhoneGappermitiendo
laejecucindecdigonativoinvocadodesdeJavascript.
ParaestetutorialnosvamosacentrarencmocrearunpluginparadispositivosAndroidquepermitaelenvodeemails
desdelaaplicacinsinnecesidaddetenerqueutilizarelgestordecorreodeAndroidysinqueelusuariotengaquedar
explcitamentea"Enviar".
2015:Volvemosala
oficina!
CursoJBossdeRedHat
Siereselresponsableo
ldertcnico,considrate
desafortunado.Nopuedes
culparanadieporsergris
3.Vamosallo
Portales,gestoresde
contenidosdocumentalesy
desarrollosamedida
Loprimeroquevamosahacerescrearnuestroplugin.Paraellovamosacrearunaestructuradecarpetasque
almacenentodosloscomponentesnecesariosparalaimplementacindelplugin.Portanntoencualquierparteque
decidamosdenuestrosistemadeficherosvamosacrearlacarpeta"sendmailcordovaplugin".
ComentandoellibroStart
upNation,Lahistoriadel
milagroeconmicodeIsrael,
deDanSenor&SaluSinger
LaformaenlaquePhoneGapsecomunicaconlapartenativaesatravsdeestallamadajavascript:
Histricodenoticias
viewplain
01.
cordova.exec(successCallback,failureCallback,class,method,[arguments]);
Estossonlosargumentos:
successCallback:serlafuncinquesequieraejecutarcuandoelresultadodelainvocacinseasatisfactorio.
failureCallback:serlafuncinaejecutarcuandoelresultadodelainvocacinnoseasatisfactorio.
class:serelnombredelaclasedenuestrocdigonativo,sintenerencuentaelnombredelpaquete.
method:serelnombredelaaccinquesevaatenerencuentaenelmtodo"execute"delaclaseanteriorque
queremosinvocar.
[arguments]]:serunarray,generalmenteenformatoJSON,dondeselepasantodoslosparmtrosdeentrada
almtodoinvocado.
http://www.adictosaltrabajo.com/tutoriales/tutoriales.php?pagina=PluginAndroidPhoneGap
ltimosTutoriales
Breveintroduccinala
Criptografa
ByteCode:Sabesloque
realmenteprogramasen
Java?
1/7
23/4/2015
CrearunpluginparaAndroidenPhoneGap
Portantoloprimeroquevamosahacerescrearnuestroficherojsconlallamadaalcdigonativo.Paraellodentrodela
carpeta"sendmailcordovaplugin"creamosotracarpetallamada"www"ydentrocreamoselfichero"sendmail.js"conel
siguientecontenido:
viewplain
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
varsendmail={
send:function(successCallback,errorCallback,subject,body,sender,password,recipients){
cordova.exec(successCallback,
errorCallback,
"SendMail",
"send",
[{
"subject":subject,
"body":body,
"sender":sender,
"password":password,
"recipients":recipients
}]
);
}
}
module.exports=sendmail;
Enlallamadaestamosindicandoquevamosatenerunaclasellamada"SendMail"conlaaccin"send"queserel
encargadoderecogerlosargumentosyrealizarelenviodelemail.Ademsfijaosenlaformadepasarlosargumentos
paraqueserecojanenformatoJSON.
Portantoelsiguientepasolgicoescrearlaclaseespecificada.Paraellodentrodelacarpeta"sendmailcordova
plugin"vamosacrearotrallamada"src"ydentrodeestaotrallamada"android"paradistinguirlasplataformasporsi
queremosextenderlafuncionalidaddeestepluginaotrasplataformassoportadascomoIOSoWindowsPhone.
Dentrodelacarpeta"android"vamosacrearelficheroSendMail.java.EnestepuntoospodisapoyarenvuestroIDE
favoritoparaimplementarelcdigo.Paralaimplementacindelmtodomeheapoyadoenuncdigoquemepas
nuestragenialmaicaconsunomenosgenialtwitter@Sara_Subidonyelnomenosnicoygenial@ifdezmolina)
viewplain
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
PopArtalestiloAndy
Warhol:Photoshop
Tcnicasderealizacinde
entrevistas
Imprimiendodocumentos
OfficeyPDFexistentescon
JavaenentornoWindows.
Batch&Print
ltimosTutorialesdel
Autor
Desarrollodeaplicaciones
mvilesmultiplataformacon
ApacheCordovautilizando
AngularJS,Ionicy
ngCordova
HooksenCordova:Cargar
todoslospluginsdeforma
automtica
Mockearlacapabackcon
Dyson
AutomatizandolosSmoke
TestconTestLinkyJenkins
SmokeTestimplementados
conTestNGySelenium
packagecom.autentia.plugin.sendmail;
importorg.apache.cordova.CallbackContext;
importorg.apache.cordova.CordovaPlugin;
importorg.json.JSONArray;
importorg.json.JSONException;
importorg.json.JSONObject;
publicclassSendMailextendsCordovaPlugin{
publicstaticfinalStringACTION_SEND="send";
publicbooleanexecute(Stringaction,JSONArrayjsonArgs,
CallbackContextcallbackContext)throwsJSONException{
try{
if(ACTION_SEND.equals(action)){
JSONObjectargs=jsonArgs.getJSONObject(0);
Stringsubject=args.getString("subject");
Stringbody=args.getString("body");
Stringsender=args.getString("sender");
Stringpassword=args.getString("password");
Stringrecipients=args.getString("recipients");
GMailSendergmailSender=newGMailSender(
sender,password);
gmailSender.sendMail(subject,body,sender,recipients);
}
callbackContext.success();
returntrue;
}catch(Exceptione){
callbackContext.error(e.getMessage());
returnfalse;
}
}
}
CategorasdelTutorial
Android
Android
ComovemosnoesmsqueunaclaseJavaqueextiendedelaclaseabstractaCordovaPluginquehacequetengaque
implementarelmtodo"execute".Enestemtododistinguimosporelnombredelaaccinquelepasamos,dependiendo
delresultadodelaaccindevolvemostrueofalseyllamaremosalcorrespondientecallback.Tambintenemosque
fijarnosencmorecuperalosargumentosdeentradaenJSONasusrespectivasvariablesString.
Estecdigotienedependenciasconotrasclasesylibrerasporlotantotenemosqueincluirlasennuestroplugin.Para
incluirlasclasesvamosacrearalamismaalturaque"SendMail.java"elfichero"GMailSender.java"elcualcontieneel
siguientecdigo:
viewplain
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
packagecom.autentia.plugin.sendmail;
importjava.io.ByteArrayInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.security.Security;
importjava.util.Properties;
importjavax.activation.DataHandler;
importjavax.activation.DataSource;
importjavax.mail.Message;
importjavax.mail.PasswordAuthentication;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
http://www.adictosaltrabajo.com/tutoriales/tutoriales.php?pagina=PluginAndroidPhoneGap
2/7
23/4/2015
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
CrearunpluginparaAndroidenPhoneGap
publicclassGMailSenderextendsjavax.mail.Authenticator{
privateStringmailhost="smtp.gmail.com";
privateStringuser;
privateStringpassword;
privateSessionsession;
static{
Security.addProvider(newJSSEProvider());
}
publicGMailSender(Stringuser,Stringpassword){
this.user=user;
this.password=password;
Propertiesprops=newProperties();
props.setProperty("mail.transport.protocol","smtp");
props.setProperty("mail.host",mailhost);
props.put("mail.smtp.auth","true");
props.put("mail.smtp.port","465");
props.put("mail.smtp.socketFactory.port","465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");
props.setProperty("mail.smtp.quitwait","false");
session=Session.getDefaultInstance(props,this);
}
protectedPasswordAuthenticationgetPasswordAuthentication(){
returnnewPasswordAuthentication(user,password);
}
publicsynchronizedvoidsendMail(Stringsubject,Stringbody,Stringsender,Stringrecipients)throwsException{
MimeMessagemessage=newMimeMessage(session);
DataHandlerhandler=newDataHandler(newByteArrayDataSource(body.getBytes(),"text/plain"));
message.setSender(newInternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if(recipients.indexOf(',')>0)
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO,newInternetAddress(recipients));
Transport.send(message);
publicclassByteArrayDataSourceimplementsDataSource{
privatebyte[]data;
privateStringtype;
publicByteArrayDataSource(byte[]data,Stringtype){
super();
this.data=data;
this.type=type;
}
publicByteArrayDataSource(byte[]data){
super();
this.data=data;
}
publicvoidsetType(Stringtype){
this.type=type;
}
publicStringgetContentType(){
if(type==null)
return"application/octetstream";
else
returntype;
}
publicInputStreamgetInputStream()throwsIOException{
returnnewByteArrayInputStream(data);
}
publicStringgetName(){
return"ByteArrayDataSource";
}
publicOutputStreamgetOutputStream()throwsIOException{
thrownewIOException("NotSupported");
}
}
}
Estaclasetieneotradepenciaconlaclase"JSSEProvider".Portantocreamosuntercerficheroalaalturadelosotros
dosllamado"JSSEProvider.java"conelsiguientecontenido:
viewplain
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
packagecom.autentia.plugin.sendmail;
importjava.security.AccessController;
importjava.security.Provider;
publicfinalclassJSSEProviderextendsProvider{
privatestaticfinallongserialVersionUID=1L;
publicJSSEProvider(){
super("HarmonyJSSE",1.0,"HarmonyJSSEProvider");
AccessController.doPrivileged(newjava.security.PrivilegedAction<Void>(){
publicVoidrun(){
put("SSLContext.TLS",
http://www.adictosaltrabajo.com/tutoriales/tutoriales.php?pagina=PluginAndroidPhoneGap
3/7
23/4/2015
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
CrearunpluginparaAndroidenPhoneGap
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1","TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
returnnull;
}
});
}
}
Loimportantedeesteejemplonoestantolaimplementacindelasolucincomoqueseveadequeformapodemos
incluirnuevasclasesylbrerasdetercerosparaeldesarrollodenuestrosplugins.Enestecasolaimplementacin
dependedecuatrolbreras:activation.jar,additional.jar,httpmime4.0.jarymail.jarlascualesvamosaincluirendentro
deunacarpeta"libs"enelmismodirectorioquelasclasesanteriores.
Enestepuntoyatenemostodoelcdigodenuestroplugin,peroahoravienelaparteimportantedecmoindicaral
proyectoquevayahacerusodenuestropluginlaformaenlaquetienequeincluirestosfuentes.
PhoneGap/Cordovaloconsigueatravsdeladefinicindelficheroplugin.xml.Esteficherocontienelainformacinde
nuestroplugincomoelnombre,lasplataformasquesoportaysobretodolainformacindedistribucindelosfuentesdel
pluginelproyectoquelovayaautilizar.
Ennuestrocasovamosacrearelficheroplugin.xmleldirectoriorazdelpluginconelsiguientecontenido:
viewplain
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
<?xmlversion="1.0"encoding="UTF8"?>
<pluginxmlns="http://www.phonegap.com/ns/plugins/1.0"
id="com.autentia.plugin.sendmail"
version="0.1.0">
<name>PluginSendMail</name>
<description>SendMailPlugin</description>
<license>MIT</license>
<keywords>phonegap,mail</keywords>
<jsmodulesrc="www/sendmail.js"name="SendMail">
<clobberstarget="sendmail"/>
</jsmodule>
<!android>
<platformname="android">
<configfiletarget="res/xml/config.xml"parent="/*">
<featurename="SendMail">
<paramname="androidpackage"value="com.autentia.plugin.sendmail.SendMail"/>
</feature>
</configfile>
<sourcefilesrc="src/android/libs/activation.jar"targetdir="libs"framework="true"/>
<sourcefilesrc="src/android/libs/additionnal.jar"targetdir="libs"framework="true"/>
<sourcefilesrc="src/android/libs/httpmime4.0.jar"targetdir="libs"framework="true"/>
<sourcefilesrc="src/android/libs/mail.jar"targetdir="libs"framework="true"/>
<sourcefilesrc="src/android/JSSEProvider.java"target
dir="src/com/autentia/plugin/sendmail"/>
<sourcefilesrc="src/android/GMailSender.java"target
dir="src/com/autentia/plugin/sendmail"/>
<sourcefilesrc="src/android/SendMail.java"targetdir="src/com/autentia/plugin/sendmail"/>
</platform>
</plugin>
Lapartemsimportantedeestadefinicinsonlos"sourcefile"dondeindicamosdondesetienenquecopiarlosfuentes
dentrodelproyectoquehaceusodelpluginyladefinicinde"jsmodule"dondeindicamoselficherojavascriptquevaa
actuardepuenteentrelaaplicacinwebyelmundonativoynospermitenotenerqueincluirelenlace"script"
explcitamentedadoqueestetiquetahacequeelcdigodelscriptseenvuelvaautomticamenteenun"closure"conlos
scopede"module","exports"y"require".Ademslaetiqueta"clobbers"conelatributo"target"indicaelnombreque
vamosautilizarparalainvocacindelosmtodosdefinidos.
Encasodequererextenderestafuncionalidadaotrasplataformastendramosquehacerladefinicindefuentesde
formasimilar.
EnestepuntoyatenemoselcdigodenuestropluginlistoparaserprobadoencualquierproyectoCordova/PhoneGap.
ParahacerusodenuestropluginvamosacrearunnuevoproyectoCordova/PhoneGap.
viewplain
01.
cordovacreateTestPlugincom.autentia.TestPlugin
EstocrearlaestructurapordefectodeunproyectoCordova.Entrandoenlacarpeta"TestPlugin"podemosaadir
nuestropluginejecutando:
viewplain
01.
cordovapluginaddPATH_RAIZ_PROYECTO_PLUGIN
Ennuestrocaso:
viewplain
01.
cordovapluginadd/Users/xxxx/Proyectos/sendmailcordovaplugin
TambinindicamosqueelproyectoqueremosquefuncioneenAndroid,ejecutando:
viewplain
01.
cordovaplatformaddandroid
Ahoraparaprobarelpluginvamosprimeroaeditarelfichero"www/index.html"paraaadirundivquepermitamostrarel
estadodelainvocacindelmtodo.Quedandoelcdigodeestaforma:
viewplain
http://www.adictosaltrabajo.com/tutoriales/tutoriales.php?pagina=PluginAndroidPhoneGap
4/7
23/4/2015
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
CrearunpluginparaAndroidenPhoneGap
<html>
<head>
<metacharset="utf8"/>
<metaname="formatdetection"content="telephone=no"/>
<!WARNING:foriOS7,removethewidth=devicewidthandheight=device
heightattributes.Seehttps://issues.apache.org/jira/browse/CB4323>
<metaname="viewport"content="userscalable=no,initialscale=1,maximumscale=1,minimum
scale=1,width=devicewidth,height=deviceheight,targetdensitydpi=devicedpi"/>
<linkrel="stylesheet"type="text/css"href="css/index.css"/>
<title>HelloWorld</title>
</head>
<body>
<divclass="app">
<h1>ApacheCordova</h1>
<divid="deviceready"class="blink">
<pclass="eventlistening">ConnectingtoDevice</p>
<pclass="eventreceived">DeviceisReady</p>
<divid="estado">ESTADO</div>
</div>
</div>
<scripttype="text/javascript"src="cordova.js"></script>
<scripttype="text/javascript"src="js/index.js"></script>
<scripttype="text/javascript">
app.initialize();
</script>
</body>
</html>
Ahoraaadimoselcdigoenelfichero"www/index.js"quehacelainvocacinalmtodoteniendoencuentaquele
tendrisquepasarvaloresvlidosdevuestracuentadeGMail.Elcdigodeesteficheroquedaradelasiguienteforma:
viewplain
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
varapp={
//ApplicationConstructor
initialize:function(){
this.bindEvents();
},
//BindEventListeners
//
//Bindanyeventsthatarerequiredonstartup.Commoneventsare:
//'load','deviceready','offline',and'online'.
bindEvents:function(){
document.addEventListener('deviceready',this.onDeviceReady,false);
},
//devicereadyEventHandler
//
//Thescopeof'this'istheevent.Inordertocallthe'receivedEvent'
//function,wemustexplicitycall'app.receivedEvent(...);'
onDeviceReady:function(){
app.receivedEvent('deviceready');
sendmail.send(app.sendMailSuccess,app.sendMailError,
'CorreoenviadoconCordova',
'EsteesunejemplodecorreoenviadoconCordova',
'tucorreo@gmail.com','supercontrasea',
'aquien@gmail.com');
},
sendMailSuccess:function(){
varestado=document.getElementById('estado');
estado.innerHTML='<p>Correoenviado</p>';
},
sendMailError:function(error){
varestado=document.getElementById('estado');
estado.innerHTML='<p>CorreoNOenviado:'+error+'</p>';
},
//UpdateDOMonaReceivedEvent
receivedEvent:function(id){
varparentElement=document.getElementById(id);
varlisteningElement=parentElement.querySelector('.listening');
varreceivedElement=parentElement.querySelector('.received');
listeningElement.setAttribute('style','display:none;');
receivedElement.setAttribute('style','display:block;');
console.log('ReceivedEvent:'+id);
}
};
Dentrodelafuncin"onDeviceReady"realizamoslallamadaanuestrafuncin.Encasodequelainvocacinsea
errneaseejecutarelmtodo"sendMailError"mostrandoenpantallaelerrorquesehaproducido.Silainvocacinse
hacecorrectamenteeldestinatariorecibirelemailyennuestraaplicacinsemostrareltexto"Correoenviado"
ParadistribuirnuestropluginsimplementesubimoslosfuentesaunacuentadeGitHub.Siquerisprobarloenvuestro
proyectoCordova/PhoneGapsolotendrisqueejecutar:
viewplain
01.
cordovapluginaddhttps://github.com/raguilera82/sendmailcordovaplugin.git
4.Conclusiones
ComovisnoescomplicadohacernuestraspropiasextensionesdefuncionalidaddeCordova/PhoneGap.
Cualquierdudaosugerenciaenlazonadecomentarios.
Saludos.
Acontinuacinpuedesevaluarlo:
Regstrateparaevaluarlo
http://www.adictosaltrabajo.com/tutoriales/tutoriales.php?pagina=PluginAndroidPhoneGap
5/7
23/4/2015
CrearunpluginparaAndroidenPhoneGap
Porfavor,vota+1ocomprtelositepareciinteresante
Share |
AdOptions
AdsbySmartSaver
AnmateycomntanosloquepiensessobreesteTUTORIAL:
Registrateyaccedeaestayotrasventajas
Fechapublicacin:2014042821:44:45
Autor:DMarkKrieg
muybuentutorial,soloteniaunaconsultaesquenesecitoguardarlostiemposdellamada(nolasllamadas)yloso
numerosalosquesellamo,peronomefunciona,(elproblemaesquemiconocimientodejavaescasinulo,porello
nologrosabercomotengoquehacerelarchivo.java)algunasugerenciadondepuedaaprenderaescribirese
archivo?,yaheh=buscadovariasfuentesperonohetenidoexitoagradeceriasusrespuestas.
EstaobraestlicenciadabajolicenciaCreativeCommonsdeReconocimientoNocomercialSinobrasderivadas2.5
IMPULSA
37
clicks
Impulsores
Comunidad
Ayuda?
2personashantradoclicksaestapgina
poweredbykarmacracy
Copyright20032015AllRightsReserved|Textolegalycondicionesdeuso|Banners|PoweredbyAutentia|Contacto
http://www.adictosaltrabajo.com/tutoriales/tutoriales.php?pagina=PluginAndroidPhoneGap
6/7
23/4/2015
CrearunpluginparaAndroidenPhoneGap
AdsbySmartSaver
http://www.adictosaltrabajo.com/tutoriales/tutoriales.php?pagina=PluginAndroidPhoneGap
AdOptions
7/7