Apache Cordova or Cordova és un framework per al desenvolupament d'aplicacions per a mòbils que permet desenvolupar apps utilitzant tecnologies web estàndard com HTML5, CSS3, i Javascript facilitant el desenvolupament multiplataforma i evitar tenir que dissenyar una aplicació per a cada plataforma nativa. Les aplicacions s'executen dins de cada plataforma utilitzant wrappers i es proporcionen APIs que compleixen amb estàndards per accedir a característiques pròpies dels dispositius com poden ser els sensors, les dades, l'estat de la xarxa, etc.
Aquest tipus d'aplicacions també són conegudes com a hybrid apps o aplicacions híbrides. Consulteu l'apartat Hybrid mobile app frameworks per conèixer altres frameworks.
Visually explained: http://www.tricedesigns.com/2012/03/22/phonegap-explained-visually/
La empresa Nitobi va donar a conèixer el projecte PhoneGap l'any 2008 al iPhoneDevCamp. El projecte va tenir molt d'èxit fins al punt que va ser comprat per Adobe al 2011 fet que va provocar un canvi d'estratègia: tot el codi de PhoneGap és va pasar a la Apache Software Foundation amb el nom de Cordova que era el carrer on Nitobi tenia la seu a Vancouver. A partir d'aquest moment Apache Cordova és converteix en el motor de Phonegap com agrada explicar a la gent d'Adobe d'una forma similar a la relació que hi ha entre el motor WebKit i Chrome.
Els dos projectes són lliures amb Adobe buscant la seva font de negoci amb un projecte de creació d'aplicacions per a mòbils una plataforma cloud que proporcionarà llibreries extres de pagament per facilitar el desenvolupament d'apps. En tot cas Apache Cordova sempre serà lliure al estar sota l'auspici de la ASF amb una Apache License v2.0 [1]
A very good explanation could be found at Ionic blog:
http://blog.ionic.io/what-is-cordova-phonegap/
Use Apache Cordova if you are:
https://www.w3.org/TR/widgets/
Apache Cordova applications rely on a common config.xml file that provides information about the app and specifies parameters affecting how it works, such as whether it responds to orientation shifts. This file adheres to the W3C's Packaged Web App, or widget, specification [2].
The application itself is implemented as a web page, by default a local file named index.html, that references whatever CSS, JavaScript, images, media files, or other resources are necessary for it to run. The app executes as a WebView within the native application wrapper, which you distribute to app stores.
The Cordova-enabled WebView may provide the application with its entire user interface. On some platforms, it can also be a component within a larger, hybrid application that mixes the WebView with native application components. (See Embedding WebViews for details.)
A plugin interface is available for Cordova and native components to communicate with each other. This enables you to invoke native code from JavaScript. Ideally, the JavaScript APIs to that native code are consistent across multiple device platforms. As of version 3.0, plugins provide bindings to standard device APIs. Third-party plugins provide additional bindings to features not necessarily available on all platforms. You can find these third-party plugins in the plugin registry and use them in your application. You can also develop your own plugins, as described in the Plugin Development Guide. Plugins may be necessary, for example, to communicate between Cordova and custom native components.
NOTA: As of version 3.0, when you create a Cordova project it does not have any plugins present. This is the new default behavior. Any plugins you desire, even the core plugins, must be explicitly added
IMPORTANT: Cordova DOES NOT provide any UI widgets or MV* frameworks. Cordova provides only the runtime in which those can execute. If you wish to use UI widgets and/or an MV* framework, you will need to select those and include them in your application yourself as third-party material. Other frameworks like Ion (see Hybrid mobile app frameworks for a list of frameworks)
The pre-requirements are:
Install Cordova:
$ sudo npm install -g cordova
Create a new app
$ mkdir github $ cd github $ mkdir cordova $ cd cordova $ cordova create hello com.example.hello HelloWorld
Then we add platform we will support:
$ cd hello $ cordova platform add android
To build app:
$ cordova build
Al platforms folder for android app is created at folder platforms:
platforms/android
NOTA: You could open this folder with Android Studio as any other Android project or...
Tou can test the app in Android using Android emulator (needs a previous AVD configured):
$ cordova emulate android
Or directly on device with (you device have to be configured and detected with adb devices command):
$ cordova run android
To generate and APK:
$ cordova build android --release
Main configuration file is config.xml.
Cordova aporta una eina per línia de comandes (CLI) que us permet gestionar els vostres projectes Cordova. Vegeu
ES poden crear nous projectes cordova a partir d'una plantilla de Github, NPM o una carpeta local
$ cordova create hello com.example.hello HelloWorld --template <npm-package-name> $ cordova create hello com.example.hello HelloWorld --template <git-remote-url> $ cordova create hello com.example.hello HelloWorld --template <path-to-template>
Per crear una nova plantilla podem utilitzar l'exemple:
https://github.com/apache/cordova-template-reference
Resources
Comprova que tinguem tot correctament configurat per a les plataformes instal·lades:
$ cordova requirements Requirements check results for android: Java JDK: installed 1.8.0 Android SDK: installed true Android target: installed android-8,android-10,android-15,android-16,android-17,android-18,android-19,android-20,android-21,android-22,android-23,android-25,Google Inc.:Google APIs:8,Google Inc.:Google APIs:10,Google Inc.:Google APIs:15,Google Inc.:Google APIs:16,Google Inc.:Google APIs:17,Google Inc.:Google APIs:18,Google Inc.:Google APIs (x86 System Image):19,Google Inc.:Google APIs:19,Google Inc.:Google APIs:21,Google Inc.:Google APIs:22,Google Inc.:Google APIs:23 Gradle: installed Requirements check results for browser: Check failed for browser due to Failed to check requirements for browser platform. check_reqs module is missing for platform. Skipping it... Error: Some of requirements check failed
Per exemple a Android podeu veure com s'utilitza la WebView amb Android_Webview#Cordova.
Els plugins es poden instal·lar utilitzant la comanda cordova plugin add. Exemple:
$ cordova plugin add cordova-plugin-device Fetching plugin "cordova-plugin-device" via npm Installing "cordova-plugin-device" for android ANDROID_HOME=/home/sergi/Android/Sdk JAVA_HOME=/usr/share/jdk1.8.0_121 Subproject Path: CordovaLib ...
Podeu consultar la llista de plugins instal·lats amb:
$ cordova plugin cordova-plugin-compat 1.1.0 "Compat" cordova-plugin-device 1.1.4 "Device" cordova-plugin-file 4.3.1 "File" cordova-plugin-whitelist 1.3.1 "Whitelist"
I totes les opcions de la comanda amb:
$ cordova plugin --help
Compte! cal tenir en compte que trobareu molts exemples a Internet amb el format anterior, per exemple dels plugins device i console:
$ cordova plugin add org.apache.cordova.device $ cordova plugin add org.apache.cordova.console
See plugins at:
https://cordova.apache.org/docs/en/4.0.0/cordova_plugins_pluginapis.md.html
You can search addtitional plugins at repo:
http://plugins.cordova.io/#/
El nom del plugin és :
cordova-plugin-device
Per instal·lar el plugin executeu:
$ cordova plugin add cordova-plugin-device
Un cop instal·lat el plugin disposem d'una variable global device amb informació del dispositiu:
document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { console.log(device.cordova); }
Info disponible:
device.cordova device.model device.platform device.uuid device.version device.manufacturer device.isVirtual device.serial
Recursos:
https://taco.visualstudio.com/en-us/docs/cordova-security-whitlists/
Possiblement el plugin més important i l'únic que està activat/instal·lat de sèrie al crear un nou projecte Cordova amb la comanda cordova create. És important destacar que des de la versió 5 de Cordova ([3]) per defecte no es permet cap mena d'accés per xarxa sense la instal·lació d'algun Plugin. Aquesta política és molt restrictiva (tot a la llista negra per defecte) i per aquesta raó el plugin whitelist (llista blanca) s'instal·lar per defecte i es permeten unes mínimes (i habituals) interaccions possibles per tal de que les aplicacions Cordova siguin funcionals.
La configuració per defecte del fitxer config.xml de Cordova és:
<plugin name="cordova-plugin-whitelist" spec="1" /> <access origin="*" /> <allow-intent href="http://*/*" /> <allow-intent href="https://*/*" /> <allow-intent href="tel:*" /> <allow-intent href="sms:*" /> <allow-intent href="mailto:*" /> <allow-intent href="geo:*" />
Nota: En antigues versions de Cordova només havia access origin="*" que era una política totalment permissiva permeten totes les formes de comunicación ja sigui per XHR/Ajax, navegació, utilitzar scripts exteriors i tots tipus de recursos de xarxa
Per tal de tenir un sistema funcional però al mateix temps segur actualment hi ha 3 opcions de control:
Si voleu mostrar/navegar a una pàgina/domini que no sigui de confiança podeu utilitzar el plugin InAppBrowser i no cal afegir el domini a allow-navigation. Aquest plugin permet obrir/navegar a dominis sense donar accés als plugins de Cordova a aquests dominis. InAppBrowser permet la navegació a qualsevol URI i a un subconjunt limitat de intents.
Cal tenir però en compte algusn detalls depenent de la plataforma:
Instal·lació (normalment no caldrà al estar definit al fitxer config.xml per defecte):
$ cordova plugin add cordova-plugin-whitelist $ cordova prepare
Per últim indicar que Cordova es basa en:
https://www.w3.org/TR/widgets-access/
Recursos:
Per qüestions de seguretat (crec TODO) no es facilita la navegació des de una pàgina web a una WebView (local content file://) i us podeu trobar amb l'error:
not allowed to load local resource file://
Quan podem necessitar aquest tipus de navegació? Per exemple per navegar a una URL externa i després tornar a l'aplicació, per exemple quan implementem el flux Oauth implicit grant. Vegeu OAuth_hybrid_apps.
Sembla ser ([4]) que pot haver diferències entre utilitzar window.open i window.location directament.
Android i configuració de la WebView:
Cal tenir en compte que només es permet l'accés a recursos locals des del sistema local vegeu setAllowFileAccess([5]) té valor true per defecte , però en canvi setAllowFileAccessFromFileURLs ([6]) esta en false per defecte.
Resources:
Llegiu abans Cordova-plugin-whitelist per entendre per a que serveix i diferenciar entre obrir pàgines a un navegador externs i dins de la WebView això com comprendre les implicacions de seguretat.
Instal·lació:
$ cordova plugin add cordova-plugin-inappbrowser
Un cop instal·lat es pot mostrar una nova URL amb:
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
Podem substituir window.open amb:
window.open = cordova.InAppBrowser.open;
És a dir que el mètode open de InAppBrowser comparteix API amb el mètode window.open de vanilla Javascript.
Es pot eliminar la sobrescritura de window.open amb:
delete window.open // Reverts the call back to it's prototype's default
I cal tenir en compte que window.open està disponible en global scope en canvi InAppBrowser només després de deviceready event.
document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { console.log("window.open works well"); }
Vegeu una possible aplicació del Plugin amb Oauth a OAuth_hybrid_apps#InAppBrowser
Resources:
$ cordova plugin add cordova-plugin-dialogs
Sobrescriure els alerts per defecte:
document.addEventListener('deviceready', function () { if (navigator.notification) { // Override default HTML alert with native dialog window.alert = function (message) { navigator.notification.alert( message, // message null, // callback "Workshop", // title 'OK' // buttonName ); }; } }, false);
Exemple alerts/dialogs natius:
Altres mètodes:
navigator.notification.alert navigator.notification.confirm navigator.notification.prompt navigator.notification.beep
Recursos:
Codi per activar (només onDeviceready):
FastClick.attach(document.body);
Resources:
Instal·lació:
$ cordova plugin add cordova-plugin-statusbar
Configuració de l'status Bar, afegir a config.xml:
<preference name="StatusBarOverlaysWebView" value="false" /> <preference name="StatusBarBackgroundColor" value="#ee6e73" /> <preference name="StatusBarStyle" value="blacktranslucent" />
Vegeu phonegap-plugin-push i l'article Android_Push_Notifications_amb_Cordova
No confondre amb canviar els dialegs/Alerts de l'aplicació i també és important entendre la diferència entre notificacions web (API web de notificacions) i Push Notifications natives de dispositiu (per exemple les enviades amb GCM a Android)
Recursos:
Resources:
Instal·lació:
$ cordova plugin add cordova-plugin-vibration
Codi:
document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { console.log(navigator.vibrate); }
navigator.vibrate, navigator.notification.vibrate
Resources:
$ cordova plugin add cordova-plugin-geolocation
Codi exemple:
this.addLocation = function(event) { event.preventDefault(); navigator.geolocation.getCurrentPosition( function(position) { alert(position.coords.latitude + ',' + position.coords.longitude); }, function() { alert('Error getting location'); }); return false; };
Resources:
$ cordova plugin add org.apache.cordova.camera
Exemple de codi:
this.changePicture = function(event) { event.preventDefault(); if (!navigator.camera) { alert("Camera API not supported", "Error"); return; } var options = { quality: 50, destinationType: Camera.DestinationType.DATA_URL, sourceType: 1, // 0:Photo Library, 1=Camera, 2=Saved Album encodingType: 0 // 0=JPG 1=PNG }; navigator.camera.getPicture( function(imgData) { $('.media-object', this.$el).attr('src', "data:image/jpeg;base64,"+imgData); }, function() { alert('Error taking picture', 'Error'); }, options); return false; };
Resources:
$ cordova plugin add cordova-plugin-contacts
Exemple codi:
this.addToContacts = function(event) { event.preventDefault(); console.log('addToContacts'); if (!navigator.contacts) { alert("Contacts API not supported", "Error"); return; } var contact = navigator.contacts.create(); contact.name = {givenName: employee.firstName, familyName: employee.lastName}; var phoneNumbers = []; phoneNumbers[0] = new ContactField('work', employee.officePhone, false); phoneNumbers[1] = new ContactField('mobile', employee.cellPhone, true); contact.phoneNumbers = phoneNumbers; contact.save(); return false; };
Recursos:
Només funcionarà amb Android! solució no multiplataforma.
Com capturar intents:
http://sciencevikinglabs.com/capturing-android-intents/
Resources:
Sistema semimanual:
https://www.red-folder.com/blog/phonegap-android-background-service
First and foremost - your Cordova applications should adopt the SPA (Single Page Application) design. Loosely defined, a SPA is a client-side application that is run from one request of a web page. The user loads an initial set of resources (HTML, CSS, and JavaScript) and further updates (showing a new view, loading data) is done via AJAX. SPAs are commonly used for more complex client-side applications. GMail is a great example of this. After you load GMail, mail views, editing, and organization are all done by updating the DOM instead of actually leaving the current page to load a completely new one.
Using a SPA can help you organize your application in a more efficient manner, but it also has specific benefits for Cordova applications. A Cordova application must wait for the deviceready event to fire before any plugins may be used. If you do not use a SPA, and your user clicks to go from one page to another, you will have to wait for deviceready to fire again before you make use of a plugin. This is easy to forget as your application gets larger.
Even if you choose not to use Cordova, creating a mobile application without using a single page architecture will have serious performance implications. This is because navigating between pages will require scripts, assets, etc., to be reloaded. Even if these assets are cached, there will still be performance issues.
Examples of SPA libraries you can use in your Cordova applications are:
PhoneGap/Apache Cordova application may only use HTML, CSS, and JavaScript. However, you can make use of network protocols (XmlHTTPRequest, Web Sockets, etc) to easily communicate with backend services written in any language. This allows your PhoneGap app to remotely access existing business processes while the device is connected to the Internet.
See also:
http://www.genbetadev.com/php/ya-se-puede-usar-php-para-desarrollar-en-android-e-ios
Format-detection meta:
<meta name="format-detection" content="telephone=no">
Serveix perquè els números de telèfon o qualsevol cosa que si pareixi no es converteixin en link per a fer una trucada.
Vegeu Content Security Policy
Hi ha opció:
$ cordova build android --release
Però no firma ni signa apk
Millor crear un fitxer anomenat ant.properties a carpeta platforms/android/ i el contingut :
key.store=/path/to/keystore/release_key_name.keystore key.alias=alias_name
I executar:
$ cordova build android --release
El fitxer es crearà a:
platforms/android/ant-build/app_name-release.apk
Altre opció?:
$ cordova build android --release -- --keystore="..\android.keystore" --storePassword=android --alias=mykeyalias=mykey
Recursos:
A partir de la versió 4.0.0 de Cordova 4.0.0 podem arribar a tindre dificultats per a connectar-nos mitjançant http a l'API. Al debuggar mitjançant chrome://inspect/#devices podrem observar el següent error:
La raó per la qual no ens funcionen les peticions és perque per defecte se permeten només les navegacions cap a les URLs file://.
La solució de l'error és afegir el següent plugin:
$ ionic plugin add https://github.com/apache/cordova-plugin-whitelist
o afegir al config.xml els protocols que ens interessen mitjançant la etiqueta <allow-navigation/> :
<allow-navigation href="http://*/*" /> <allow-navigation href="https://*/*" /> <allow-navigation href="data:*" />