Cordova - PhoneGap

From Sinfronteras
Revision as of 17:44, 15 October 2019 by Adelo Vieira (talk | contribs) (Test the App)
Jump to: navigation, search

https://cordova.apache.org/

https://phonegap.com

Apache Cordova/PhoneGap enables software programmers to build applications for mobile devices using CSS3, HTML5, and JavaScript instead of relying on platform-specific APIs like those in Android, iOS, or Windows Phone. It enables wrapping up of CSS, HTML, and JavaScript code depending upon the platform of the device. It extends the features of HTML and JavaScript to work with the device. The resulting applications are hybrid, meaning that they are neither truly native mobile application (because all layout rendering is done via Web views instead of the platform's native UI framework) nor purely Web-based (because they are not just Web apps, but are packaged as apps for distribution and have access to native device APIs).


Is PhoneGap equal to Cordova? https://www.businessofapps.com/news/apache-cordova-adobe-phonegap-know-real-differences/

PhoneGap is a distribution of Apache Cordova. So Apache Cordova serves as the engine to power PhoneGap just like WebKit is an engine that powers Chrome and Safari (iOS browser). Nonetheless, as an app developer or as an organization, you don't have to worry about the differences between these two. The story is like this:

  • PhoneGap was previously a product of Adobe.
  • To keep it open-source always and follow standards, PhoneGap codebase was handed over to Apache.
  • At Apache, it got a name change as Cordova.
  • And now it’s better known as Apache Cordova.

The most important to understand here is that PhoneGap is powered by apache Cordova. PhoneGap is Cordova plus some extra Adobe stuff. If you are developing a hybrid mobile app, you can either create it using proper Cordova or choose Adobe's ecosystem for using PhoneGap distribution of Cordova.

The open-source Cordova/PhoneGap will be always free and delivered by Apache. Over time, Adobe may add values to this (current) codebase that consists of other Adobe services and that will be named as PhoneGap, which will be chargeable.



Installing Cordova

https://cordova.apache.org/docs/en/latest/guide/cli/


The Cordova command-line tool is distributed as an npm package.


  • Install Cordova with NPM:
sudo npm install -g cordova

The -g flag above tells npm to install cordova globally. Otherwise it will be installed in the node_modules subdirectory of the current working directory.


  • Check Cordova Version:
cordova --version


If you don't already have one. Following installation, you should be able to invoke git on your command line. The CLI uses it to download assets when they are referenced using a url to a git repo.



Using Cordova

https://cordova.apache.org/docs/en/latest/guide/cli/



Create the App - Project folder

https://cordova.apache.org/docs/en/latest/guide/cli/

Execute the below command to create an «Cordova application environment/Project folder»:

cordova create myapp

or using the entire syntax:

cordova create path [id [name [config]]] [options]
cordova create hello com.example.hello HelloWorld


This creates the required directory structure for your cordova app. By default, the cordova create script generates a skeletal web-based application whose home page is the project's www/index.html file.



Add platforms

Now add the required platform in your application. This will create required files for the corresponding platform under the platforms/android and platforms/ios directories (may be necessary to use sudo):

cd myapp
cordova platform add ios
cordova platform add android
cordova platform add browser

If we want to test in the browser (using the command «cordova serve»), it is very important to add the browser platform. Otherwise, you will have some very annoying pop up messages (gap_init, for example) every time you refresh the browser.


Use below command to list the installed and available platforms for Cordova application:

cordova platform -ls


If you accidentally added any platform which you no longer needs, just remove that using commands like below:

cordova platform remove ios
cordova platform remove android



Preview your App

https://cordova.apache.org/docs/en/latest/reference/cordova-cli/#cordova-serve-command


At this point, you can just go to «.../www/index.html» to preview your App in the Web Browser.


You can also use the «cordova serve» command to run a local web server using specified port or default of 8000.

cordova serve

Then you can preview your App in the Web Browser at:

http://localhost:PORT/
http://localhost:8000/
  • Then, we have to choose the platform.


Or directly at:

http://localhost:PORT/PLATFORM/www
http://localhost:8000/android/www/



Preview on a Mobile Device using PhoneGap CLI

http://docs.phonegap.com/getting-started/4-preview-your-app/cli/

You can use the PhoneGap CLI to immediately preview your app on a device without installing platform SDKs, registering devices, or compiling code. The PhoneGap CLI (using the command «phonegap serve») starts a small web server to host your project and returns the server address for you to pair with from the PhoneGap Developer App running on your mobile device.

phonegap serve



Install pre-requisites for building

To build and run apps, you need to install SDKs for each platform you wish to target. Alternatively, if you are using browser for development you can use browser platform which does not require any platform SDKs.

To check if you satisfy requirements for building the platform:

cordova requirements


Android platform requirements

https://cordova.apache.org/docs/en/latest/guide/platforms/android/index.html#requirements-and-support



Java Development Kit - JDK

See Java



Gradle
sudo apt install gradle



Android SDK


Installation:

  • Go to the Android Studio official page: https://developer.android.com/studio/index.html
  • Download and unzip the sdk-tools-linux zip file.
  • To complete the installation we need to add the paths of the bin folder to our PATH environment variable:

.bashrc

PATH=/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/tools:$PATH
PATH=/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/tools/bin:$PATH


  • We can also do it using apt. However, when I did id with apt, I was not able to find the sdkmanager command in my system. So I recommended to do it by downloading the zip file from the official page.
sudo apt install android-sdk



Adding SDK Packages:

After installing the Android SDK, you must also install the packages for whatever API level you wish to target. It is recommended that you install the highest SDK version that your version of cordova-android supports (see Requirements and Support).

Open the Android SDK Manager (Tools > SDK Manager in Android Studio, or sdkmanager on the command line), and make sure the following are installed:

  • Android Platform SDK for your targeted version of Android
  • Android SDK build-tools version 19.1.0 or higher
  • Android Support Repository (found under the "SDK Tools" tab)

See Android's documentation on Installing SDK Packages for more details: https://developer.android.com/studio/command-line/sdkmanager


Esta fue la parte más complicada. Si no se instalan los package necesarios en esta parte, la ejecución del comando «cordova requirements» no encontrará la instalación e «Android target». Esto creo que lo solucioné de esta forma:

sdkmanager "build-tools;29.0.0" "platform-tools" "platforms;android-28"



Setting environment variables

https://cordova.apache.org/docs/en/latest/guide/platforms/android/index.html#setting-environment-variables

Cordova's CLI tools require some environment variables to be set in order to function correctly. The CLI will attempt to set these variables for you, but in certain cases you may need to set them manually. The following variables should be updated:
  • Set the JAVA_HOME environment variable to the location of your JDK installation: See Java
  • Set the ANDROID_HOME environment variable to the location of your Android SDK installation:
export ANDROID_HOME=/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/
  • It is also recommended that you add the Android SDK's tools, tools/bin, and platform-tools directories to your PATH:
Al instalar Android SDK, el zip file sdk-tools-linux descargado de la página oficial, sólo contiene el directorio tools. No contiene ningún directorio platform-tools. Es por eso que es muy importante «Adding SDK Packages» como se describió arriba. A través de «sdkmanager» se isntalan los paquetes y adicionan los directorios correspondientes («android-sdk/platform-tools» and «android-sdk/build-tools») (https://cordova.apache.org/docs/en/latest/guide/platforms/android/index.html#setting-environment-variables):
export PATH=${PATH}:/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/platform-tools
export PATH=${PATH}:/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/build-tools
export PATH=${PATH}:/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/build-tools/29.0.0


Luego de todas las configuraciones realizadas en esta parte, se adicionaron las siguientes líneas al «/home/adelo/.bashrc» y «/root/.bashrc». Es muy importante señalar que las configuraciones las he colocado también en «/root/.bashrc» porque he tenido que ejecutar algunos comandos como root por questiones de permisología («cordova build android», por ejemplo).

«/home/adelo/.bashrc» & «/root/.bashrc»:

# Android SDK:
PATH=/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/tools:$PATH
PATH=/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/tools/bin:$PATH


# Cordova - Android platform requirements:
#* Set the ANDROID_HOME environment variable to the location of your Android SDK installation:
export ANDROID_HOME=/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/
#* It is also recommended that you add the Android SDK's tools, tools/bin, and platform-tools directories to your PATH:
export PATH=${PATH}:/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/platform-tools
export PATH=${PATH}:/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/build-tools
export PATH=${PATH}:/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/build-tools/29.0.0



Build the Cordova Application

On all requirements completed successfully, run the build command to build your application:

cordova build              ## Build all added platforms 
cordova build android      ## Build for specific platform

Antes de ejecutar el comando anterior, tuve que iniciar modo root: «sudo su». Luego: «cordova build android». A través de «cordova build android» no fue capaz de ejecutar este paso con éxito.


The «cordova build» command is a shortcut for «cordova prepare» + «cordova compile» commands. It Allows you to build the app. This procedure will compile the code and build the executable file for the specific platform. In the case of an Android platform, it will build a .apk file.



Using Phonegap Build

https://build.phonegap.com/apps

This is an online service that we can use to build the App. If we don't have all the requirements (packages installed) in or computer to be able to build (compile) the App, we can use https://build.phonegap.com/apps. In this Web site, we can upload our code and it will build the App and return the executable file (.apk file in case of Android app).

We can also use Adobe® PhoneGap™ Build Web site to build our App. As is written in this Web Site, we just have to upload our HTML5, CSS, and JavaScript assets to the Adobe® PhoneGap™ Build cloud service and it do the work of compiling the code.



What is an APK File

An Android Package Kit (APK for short) is the package file format used by the Android operating system for distribution and installation of mobile apps. Just like Windows (PC) systems use an .exe file for installing software, the APK does the same for Android.



Test the App - Deploys app on specified platform devices or emulators

https://cordova.apache.org/docs/en/latest/guide/cli/#test-the-app



On an emulators from Android Studio

cordova emulate android



On a physical device

https://developer.android.com/studio/run/device

https://developer.android.com/studio/command-line/adb.html#issuingcommands

cordova run
cordova run android

«cordova run» prepares, builds, and deploys app on specified platform devices/emulators. If a device is connected it will be used, unless an eligible emulator is already running.


Before «cordova run» we need:

  • Connect the device over a USB cable.
  • To set up the device for testing, following procedures that vary for each platform:
  • In my phone: Settings > Developper options: USB debugging (On)
  • Target the device using the adb command:
https://developer.android.com/studio/run/device
https://developer.android.com/studio/command-line/adb.html#issuingcommands
https://riptutorial.com/android/example/8560/direct-adb-command-to-specific-device-in-a-multi-device-setting


To display the display the list of devices attached:
adb devices # Dispay devices connected by serial number


Then, to target a device by serial number
adb -s <device> <command>
adb -s W3D7N16328008017 shell



Structure of the Project folder - Some important files

By default, «cordova create» script generates a skeletal web-based application whose start page is the project's www/index.html file. Any initialization should be specified as part of the device ready event handler defined in www/js/index.js


Some important files in the project folder:

  • config.xml:
Inside of the application code, there is a very simple file called config.xml that is used to tell your application which libraries it can use.
  • plugins folder:
Here you can see a list of folders that each contain the tools for the different plugins.



Plugins


Adding plugins

https://cordova.apache.org/docs/en/latest/guide/cli/index.html#add-plugins

You can modify the default generated app to take advantage of standard web technologies, but for the app to access device-level features, you need to add plugins.

A plugin exposes a Javascript API for native SDK functionality. Plugins are typically hosted on npm. Some key APIs are provided by the Apache Cordova open source project and these are referred to as Core Plugin APIs. You can also use the CLI to launch the search page.

You can search for them on the plugin search page: https://cordova.apache.org/plugins/


To add a plugin, we can use the «cordova plugin add» command. For example:

cordova plugin add cordova-plugin-camera
Fetching plugin "cordova-plugin-camera@~2.1.0" via npm
Installing "cordova-plugin-camera" for android
Installing "cordova-plugin-camera" for ios

Plugins can also be added using a directory or a git repo.

The «cordova plugin add» command will add and save the corresponding plugin to config.xml and package.json.


to view currently installed plugins:

cordova plugin ls
// or
cordova plugin 



Vibration plugin

https://www.npmjs.com/package/cordova-plugin-vibration


Installation:

cordova plugin add cordova-plugin-vibration


This plugin defines global objects including navigator.vibrate.

Although in the global scope, they are not available until after the «deviceready» event:

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
    console.log(navigator.vibrate);
}


Vibrates the device for a given amount of time:

navigator.vibrate(time);
navigator.vibrate(3000);

time: Milliseconds to vibrate the device. (Number)


Example:

index.js
function shake(){
    navigator.vibrate(3000);
}


index.html
<button onclick="shake()"> Vibrate </button>



Camera plugin

https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-camera/


Installation:

This requires cordova 5.0+

cordova plugin add cordova-plugin-camera


This plugin defines a global navigator.camera object, which provides an API for taking pictures and for choosing images from the system's image library.

Although the object is attached to the global scoped navigator, it is not available until after the deviceready event:

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
    console.log(navigator.camera);
}


camera.getPicture(successCallback, errorCallback, options)

Takes a photo using the camera, or retrieves a photo from the device's image gallery. The image is passed to the success callback as a Base64-encoded String, or as the URI for the image file.

Example: