<<

Hybrid Mobile Application - Apache Cordova Framework

Hybrid Mobile Application - Apache Cordova Framework

Hybrid Mobile Application - Framework

주) 혜안정보통신 김진승 ( [email protected] ) AGENDA 2 / 74

1. Apache Cordova

2. Hello World

3. Environment for development

4. jQuery Integration

5. Create plugins For Cordova 1.Apache Cordova - Overview 3 / 74

• Apache Cordova is an open-source mobile development framework.

• It allows you to use standard web technologies - HTML5, CSS3, and JavaScript for cross-platform development.

• Applications execute within wrappers targeted to each platform, and rely on standards-compliant API bindings to access each device's capabilities such as sensors, data, network status, etc. 1.Apache Cordova - Architecture 4 / 74 1.Apache Cordova - Plugins 5 / 74

• They provide an interface for Cordova and native components to communicate with each other and bindings to standard device .

• This enables you to invoke native code from JavaScript.

• You can search for Cordova plugins using plugin search or npm.

• Plugins may be necessary, for example, to communicate between Cordova and custom native components. 1.Apache Cordova - Workflow(1/3) 6 / 74

Cross-platform (CLI) workflow:

• if you want your app to run on as many different mobile operating systems as possible, with little need for platform-specific development.

• This workflow centers around the cordova CLI. The CLI is a high-level tool that allows you to build projects for many platforms at once, abstracting away much of the functionality of lower-level shell scripts.

• The CLI copies a common set of web assets into subdirectories for each mobile platform, makes any necessary configuration changes for each, runs build scripts to generate application binaries. 1.Apache Cordova - Workflow(2/3) 7 / 74

Platform-centered workflow • if you want to focus on building an app for a single platform and need to be able to modify it at a lower level.

• if you want your app to mix custom native components with web-based Cordova components.

• As a rule of thumb, use this workflow if you need to modify the project within the SDK.

• While you can use this workflow to build cross-platform apps, it is generally more difficult because the lack of a higher-level tool means separate build cycles and plugin modifications for each platform.

• https://cordova.apache.org/docs/en/latest/guide/platforms/android/webview. 1.Apache Cordova - Workflow(3/3) 8 / 74

UI Design Project Creation FrontEnd Programming Source Optimization for Android Deployment for Android Build with HTML5 (Android market) Final Build HTML5, CSS3, JS Apache Cordova

Source Optimization for iOS Deployment for iOS (Apple Appstore) Final Build

BackEnd Programming PHP, ASP, PERL, Binding PYTHON, Node.JS... REST SOAP JSON XML RSS DBMS MySql,MS-SQL, HTTP Postgresql, Oracle…

DevelopTools for working UI Design & FronEnd Programming : Text Editor ( EditPlus, UltraEdit, AcroEdit, TextWrangler…..), Web Editor Project Creation : Node.js, cordova CLI(CommandLineInterface) Source Optimization for Android : Android Studio, Eclipse Source Optimization for iOS : Xcode BackEndProgramming : Text Editor ( EditPlus, UltraEdit, AcroEdit, TextWrangler…..) 1.Apache Cordova - Installing Cordova(1/8) 9 / 74

Requirements

Common Android iOS Node.js Java JDK Apple OS X Cordova Android SDK XCode Android Studio 1.Apache Cordova - Installing Cordova(2/8) 10 / 74

Node.js

Node.js®는 Chrome V8 JavaScript 엔진으로 빌드된 JavaScript 런타임입니다. Node.js는 이벤트 기반, 논 블로킹 I/ O 모델을 사용해 가볍고 효율적입니다. Node.js의 패키지 생태 계인 npm은 세계에서 가장 큰 오픈 소스 라이브러리이기도 합 니다. 1.Apache Cordova - Installing Cordova(3/8) 11 / 74

Node.js

• 비동기 I/O 처리 / 이벤트 위주: Node.js 라이브러리의 모든 API는 비동기식입니다, 멈추지 않는다는거죠 (Non-blocking). Node.js 기반 서버는 API가 실행되었을때, 데이터를 반환할 때까지 기다리지 않고 다음 API 를 실행합니다. 그리고 이전에 실행했던 API가 결과값을 반 환할 시, NodeJS의 이벤트 알림 메커니즘을 통해 결과값을 받아옵니다.

• 빠른 속도: 구글 크롬의 V8 자바스크립트 엔진을 사용하여 빠른 코드 실행을 제공합니다.

• 단일 쓰레드 / 뛰어난 확장성: Node.js는 이벤트 루프와 함께 단일 쓰레드 모델을 사용합니 다. 이벤트 메커니즘은 서버가 멈추지않고 반응하도록 해주어 서버의 확장성을 키워줍니다. 반면, 일반적인 웹서버는 (Apache) 요청을 처리하기 위하여 제한된 쓰레드를 생성합니다. Node.js 는 쓰레드를 한개만 사용하고 Apache 같은 웹서버보다 훨씬 많은 요청을 처리할 수 있습니다.

• 노 버퍼링: Node.js 어플리케이션엔 데이터 버퍼링이 없고, 데이터를 chunk로 출력합니다.

• 라이센스: Node.js 는 MIT License가 적용되어있습니다. 1.Apache Cordova - Installing Cordova(4/8) 12 / 74

Node.js - Node Package Manager (NPM)

• NPMSearch 에서 탐색 가능한 Node.js 패키지/모듈 저장소 • Node.js 패키지 설치 및 버전 / 호환성 관리를 할 수 있는 커맨 드라인 유틸리티

npm search 1.Apache Cordova - Installing Cordova(5/8) 13 / 74

Node.js - Installing

https://nodejs.org/en/download/ 1.Apache Cordova - Installing Cordova(6/8) 14 / 74

1. Download and install Node.js. On installation you should be able to invoke node and npm on your command line.

2. (Optional) Download and install a git client, 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.

3. Install the cordova module using npm utility of Node.js. The cordova module will automatically be downloaded by the npm utility. 1.Apache Cordova - Installing Cordova(7/8) 15 / 74

• on OS X and :

$ sudo npm install -g cordova

On OS X and Linux, prefixing the npm command with sudo may be necessary to install this development utility in otherwise restricted directories such as /usr/ local/share. If you are using the optional nvm/nave tool or have write access to the install directory, you may be able to omit the sudo prefix. There are more tips available on using npm without sudo, if you desire to do that. 1.Apache Cordova - Installing Cordova(8/8) 16 / 74

• on Windows:

C:\>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.

Following installation, you should be able to run cordova on the command line with no arguments and it should print help text. 1.Apache Cordova - Checking Cordova(1/3) 17 / 74 cordova installation status 1.Apache Cordova - Checking Cordova(2/3) 18 / 74

Global Commands create ...... Create a project help ...... Get help for a command telemetry ...... Turn telemetry collection on or off

Project Commands info ...... Generate project information requirements ...... Checks and print out all the requirements for platforms specified

platform ...... Manage project platforms plugin ...... Manage project plugins

prepare ...... Copy files into platform(s) for building compile ...... Build platform(s) clean ...... Cleanup project from build artifacts

run ...... Run project (including prepare && compile) serve ...... Run project with a local webserver (including prepare) 1.Apache Cordova - Checking Cordova(3/3) 19 / 74 cordova Project Commands jinseungkimui-MacBook-Pro:~ jinseungkim$ cordova requirements Error: Current working directory is not a Cordova-based project. jinseungkimui-MacBook-Pro:~ jinseungkim$ jinseungkimui-MacBook-Pro:npc jinseungkim$ ls config.xml hooks plugins cordova_create_kra.rtf platforms www jinseungkimui-MacBook-Pro:npc jinseungkim$ cordova requirements

Requirements check results for android: Java JDK: installed 1.8.0 Android SDK: installed Android target: installed android-21,android-22,android-23,android-24,android-25 Gradle: installed

Requirements check results for : Apple OS X: installed darwin Xcode: installed 8.2 ios-deploy: not installed ios-deploy was not found. Please download, build and install version 1.8.3 or greater from https://github.com/phonegap/ios- deploy into your path, or do 'npm install -g ios-deploy' Error: Some of requirements check failed jinseungkimui-MacBook-Pro:npc jinseungkim$ 2.Hello World - create project 20 / 74

cordova create path [id [name [config]]] [options]

$ cordova create hello kr.co.rcube.hello HelloWorld Creating a new cordova project.

hello ├── config.xml ├── hooks │ └── README.md ├── platforms ├── plugins └── www ├── │ └── index.css ├── img │ └── logo.png ├── index.html └── js └── index.js

7 directories, 6 files 2.Hello World - Config.xml(1/2) 21 / 74

• Config.xml is a global configuration file that controls many aspects of a cordova application's behavior.

• This platform-agnostic XML file is arranged based on the W3C's Packaged Web Apps (Widgets) specification, and extended to specify core Cordova API features, plugins, and platform-specific settings.

• When using the CLI to build a project, versions of this file are passively copied into various platforms/ subdirectories. 2.Hello World - Config.xml(2/2) 22 / 74

HelloWorld A sample Apache Cordova application that responds to the deviceready event. Apache Cordova Team configuration for WhitelistPlugin 2.Hello World - index.js 23 / 74 var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler onDeviceReady: function() { app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received');

listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;');

console.log('Received Event: ' + id); } }; app.initialize(); 2.Hello World - Add platform(1/2) 24 / 74

Add the platforms that you want to target your app. We will add the 'ios' and 'android' platform and ensure they get saved to config.xml and package.json: $ cordova platform add ios Adding ios project... Creating Cordova project for the iOS platform: Path: platforms/ios Package: kr.co.rcube.hello Name: HelloWorld iOS project created with [email protected] Discovered plugin "cordova-plugin-whitelist" in config.xml. Adding it to the project Fetching plugin "cordova-plugin-whitelist@1" via npm Installing "cordova-plugin-whitelist" for ios jinseungkimui-MacBook-Pro:hello jinseungkim$ cordova platform add android Adding android project... Creating Cordova project for the Android platform: Path: platforms/android Package: kr.co.rcube.hello Name: HelloWorld Activity: MainActivity Android target: android-23 Android project created with [email protected] Installing "cordova-plugin-whitelist" for android

This plugin is only applicable for versions of cordova- android greater than 4.0. If you have a previous platform version, you do *not* need this plugin since the whitelist will be built in. 2.Hello World - Add platform(2/2) 25 / 74

$ cordova platform ls Installed platforms: android 5.2.2 ios 4.2.1 Available platforms: amazon-fireos ~3.6.3 (deprecated) blackberry10 ~3.8.0 browser ~4.1.0 firefoxos ~3.6.3 osx ~4.0.1 ~3.7.0 hello ├── config.xml ├── hooks │ └── README.md ├── platforms │ ├── android │ ├── ios │ └── platforms.json ├── plugins │ ├── android.json │ ├── cordova-plugin-whitelist │ ├── fetch.json │ └── ios.json └── www ├── css ├── img ├── index.html └── js 2.Hello World - prepare command 26 / 74

$ cordova prepare [target platform]

. ├── plugins ├── config.xml │ ├── android.json ├── hooks │ ├── cordova-plugin-whitelist │ └── README.md │ │ ├── CONTRIBUTING.md ├── platforms │ │ ├── LICENSE │ ├── android │ │ ├── NOTICE │ │ ├── AndroidManifest.xml │ │ ├── README.md │ │ ├── CordovaLib │ │ ├── RELEASENOTES.md │ │ ├── android.json │ │ ├── doc │ │ ├── assets │ │ ├── package.json │ │ ├── build │ │ ├── plugin.xml │ │ ├── build.gradle │ │ └── src │ │ ├── cordova copy │ ├── fetch.json │ │ ├── gradle │ └── ios.json │ │ ├── gradlew └── www │ │ ├── libs ├── css │ │ ├── platform_www │ └── index.css │ │ ├── project.properties ├── img │ │ ├── res │ └── logo.png │ │ ├── settings.gradle ├── index.html │ │ └── src └── js │ ├── ios copy └── index.js │ │ ├── CordovaLib │ │ ├── HelloWorld │ │ ├── HelloWorld.xcodeproj │ │ ├── build │ │ ├── cordova │ │ ├── ios.json │ │ ├── platform_www │ │ └── www │ └── platforms.json 2.Hello World - build 27 / 74

• 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 deviceready event handler defined in www/js/index.js

$ cordova build

$ cordova build [target platform] 2.Hello World - Test the App(1/2) 28 / 74

1. create the cordova project 2. add platforms 3. prepare the cordova project 4. test the app (1) launch the virtual device (2) run test command

$ cordova emulate android 2.Hello World - Test the App(2/2) 29 / 74

$ cordova emulate ios 2.Hello World - Add Plugins(1/4) 30 / 74

• A plugin exposes a Javascript API for native SDK functionality.

• Plugins are typically hosted on npm and you can search for them on the plugin search page.

• Some key APIs are provided by the Apache Cordova open source project and these are referred to as Core Plugin APIs. 2.Hello World - Add Plugins(2/4) 31 / 74

$ cordova plugin search battery 2.Hello World - Add Plugins(3/4) 32 / 74

• To add and save the battery-status plugin to config.xml and package.json, we will specify the npm package name for the battery-status plugin

$ cordova plugin add cordova-plugin-battery-status Fetching plugin "cordova-plugin-battery-status" via npm Installing "cordova-plugin-battery-status" for android Installing "cordova-plugin-battery-status" for ios

$ cordova plugin ls cordova-plugin-battery-status 1.2.4 "Battery" cordova-plugin-whitelist 1.3.2 "Whitelist" 2.Hello World - Add Plugins(4/4) 33 / 74

$ cordova plugin add cordova-plugin-camera hello/plugins hello/plugins ├── android.json ├── android.json ├── cordova-plugin-whitelist ├── cordova-plugin-battery-status │ ├── CONTRIBUTING.md │ ├── CONTRIBUTING.md │ ├── LICENSE │ ├── LICENSE │ ├── NOTICE │ ├── NOTICE │ ├── README.md │ ├── README.md │ ├── RELEASENOTES.md │ ├── RELEASENOTES.md │ ├── doc │ ├── doc │ ├── package.json │ ├── package.json │ ├── plugin.xml │ ├── plugin.xml │ └── src │ ├── src ├── fetch.json │ ├── tests └── ios.json │ ├── types │ └── www ├── cordova-plugin-whitelist │ ├── CONTRIBUTING.md │ ├── LICENSE │ ├── NOTICE │ ├── README.md │ ├── RELEASENOTES.md │ ├── doc │ ├── package.json │ ├── plugin.xml │ └── src ├── fetch.json └── ios.json 2.Hello World - Plugins Release 34 / 74

• cordova-plugin-battery-status: 1.1.2 • cordova-plugin-camera: 2.2.0 • cordova-plugin-console: 1.0.3 • cordova-plugin-contacts: 2.1.0 • cordova-plugin-device: 1.1.2 • cordova-plugin-device-motion: 1.2.1 • cordova-plugin-device-orientation: • cordova-plugin-dialogs: 1.2.1 • cordova-plugin-file: 4.2.0 • cordova-plugin-file-transfer: 1.5.1 • cordova-plugin-geolocation: 2.2.0 • cordova-plugin-inappbrowser: 1.4.0 • cordova-plugin-media: 2.3.0 • cordova-plugin-media-capture: 1.3.0 • cordova-plugin-network-information: 1.2.1 • cordova-plugin-splashscreen: 3.2.2 • cordova-plugin-statusbar: 2.1.3 • cordova-plugin-test-framework: 1.1.2 • cordova-plugin-vibration: 2.1.1 • cordova-plugin-whitelist: 1.2.2 • cordova-plugin-wkwebview-engine: 1.0.3 • cordova-plugin-compat: 1.0.0 2.Hello World - Customizing each platform(1/5) 35 / 74

• While Cordova allows you to easily deploy an app for many different platforms, sometimes you need to add customizations. In that case, you don't want to modify the source files in various www directories within the top-level platforms directory, because they're regularly replaced with the top-level www directory's cross-platform source.

• the top-level merges directory offers a place to specify assets to deploy on specific platforms. Each platform- specific subdirectory within merges mirrors the directory structure of the www source tree, allowing you to override or add files as needed. 2.Hello World - Customizing each platform(2/5) 36 / 74

hello hello ├── config.xml ├── config.xml ├── hooks ├── hooks │ └── README.md │ └── README.md ├── platforms ├── merges ├── plugins │ ├── android └── www │ └── ios ├── css ├── platforms │ └── index.css ├── plugins ├── img └── www │ └── logo.png ├── css ├── index.html │ └── index.css └── js ├── img └── index.js │ └── logo.png ├── index.html └── js └── index.js

1. create the top-level merges directory 2. create a [platform name] subdirectory within “merges” 3. create a [www sub category] subdirectory within each platform directory 2.Hello World - Customizing each platform(3/5) 37 / 74 hello ├── merges │ └── android │ └── css │ └── overrides.css body { font-size:12px; } └── www ├── css │ ├── overrides.css body { font-size:10px; } │ └── index.css ├── img │ └── logo.png ├── index.html └── js └── index.js

$ cordova build 2.Hello World - Customizing each platform(4/5) 38 / 74 hello/platforms/android/assets └── www ├── cordova-js-src │ ├── android │ │ ├── nativeapiprovider.js │ │ └── promptbasednativeapi.js │ ├── exec.js │ ├── platform.js │ └── plugin │ └── android │ └── app.js ├── cordova.js ├── cordova_plugins.js ├── css │ ├── index.css │ └── overrides.css body { font-size:12px; } ├── img │ └── logo.png ├── index.html ├── js │ ├── common.js │ └── index.js └── plugins └── cordova-plugin-battery-status └── www └── battery.js 2.Hello World - Customizing each platform(5/5) 39 / 74 hello/platforms/ios/www ├── cordova-js-src │ ├── exec.js │ └── platform.js ├── cordova.js ├── cordova_plugins.js ├── css │ ├── index.css │ └── overrides.css body { font-size:10px; } ├── img │ └── logo.png ├── index.html ├── js │ ├── common.js │ └── index.js └── plugins └── cordova-plugin-battery-status └── www └── battery.js 3.Environment for development - Mobile Web 40 / 74

Client side Server side

send

coding TextWrangler Apache view

data connection Chrome Device Mode 3.Environment for development - Hybrid App 41 / 74

Client side Server side

Apache Chrome TextWrangler 1. Build Mobile Web

2. Build Hybrid App using Cordova

3. Customizing each platform Android Studio XCode 4.jQuery Integration - downloading jQuery(1/2) 42 / 74

http://jquerymobile.com/ 4.jQuery Integration - downloading jQuery(2/2) 43 / 74 .mobile-1.4.5 ├── demos directory for demos of jquery-mobile ├── images directory of images ├── jquery.mobile-1.4.5.css Uncompressed with Default theme ├── jquery.mobile-1.4.5.js Uncompressed ├── jquery.mobile-1.4.5.min.css Minified with Default theme ├── jquery.mobile-1.4.5.min.js Minified ├── jquery.mobile-1.4.5.min.map source map ├── jquery.mobile.external-png-1.4.5.css uses external png files for icons ├── jquery.mobile.external-png-1.4.5.min.css ├── jquery.mobile.icons-1.4.5.css specifies icons only ├── jquery.mobile.icons-1.4.5.min.css ├── jquery.mobile.inline-png-1.4.5.css specifies inline png files using base64 ├── jquery.mobile.inline-png-1.4.5.min.css ├── jquery.mobile.inline-svg-1.4.5.css specifies inline svg files using base64 ├── jquery.mobile.inline-svg-1.4.5.min.css ├── jquery.mobile.structure-1.4.5.css Uncompressed structure without a theme ├── jquery.mobile.structure-1.4.5.min.css Minified structure without a theme ├── jquery.mobile.theme-1.4.5.css Uncompressed theme for structure without theme └── jquery.mobile.theme-1.4.5.min.css Minified theme for structure without theme 4.jQuery Integration - skeleton(1/2) 44 / 74 skeleton

EXAMPLE ├── css │ ├── images │ │ └── ajax-loader.gif │ └── jquery.mobile-1.4.5.css ├── images ├── index.html └── js ├── jquery.js └── jquery.mobile-1.4.5.js

jQuery Mobile Demos Contents goes here.... 4.jQuery Integration - skeleton(2/2) 45 / 74

4.jQuery Integration - Chrome device mode 46 / 74 4.jQuery Integration - Build the pages on cordova 47 / 74 cordova project root cordova project root hello EXAMPLE ├── config.xml ├── css ├── hooks 1 │ ├── images ├── merges │ │ └── ajax-loader.gif ├── platforms │ └── jquery.mobile-1.4.5.css ├── plugins ├── images └── www ├── index.html └── js ├── jquery.js └── jquery.mobile-1.4.5.js

2 $ cordova build 3

$ cordova emulate android $ cordova emulate ios android ios 4.jQuery Integration - Events(1/3) 48 / 74 mobileinit jQuery 모바일이 초기화되었을 때 발생하는 이벤트. 페이지 내에서 최초 한 번만 발생하며, JQM 스크립트를 추가하기 전에 할당해야 한다. 주로, 글로벌 설정을 위한 용도로 사용한다. pagebeforechange 페이지가 로딩되거나 트랜지션 하기 전에 발생하는 이벤트. toPage에 대한 정보를 가지고 있으며, 이 이벤트에서 목적지 정보를 변경하거나 이벤트를 중지할 수 있다. pagebeforeload 페이지를 로드하기 전에 발생하는 이벤트. XHR 요청을 보내기 전에 발생한다. pagebeforecreate 페이지 엘리먼트가 추가되었으며, JQM 플러그인이나 위젯이 초기화되기 전 플러그인이나 위젯이 초기화되기 전에 DOM을 추가하려고 한다면 이 이벤트를 사용한다. 예를 들어, 자바스크립트로 DOM을 만들어 추가하려고 하는 경우. 4.jQuery Integration - Events(2/3) 49 / 74 pagecreate 각 위젯 초기화가 완료된 후 호출되는 이벤트. pageinit 모든 위젯의 초기화가 완료된 후 호출되는 이벤트. 정확히는 모르겠으나, pagecreate는 각각의 위젯이 초기화되면서 호출되는 거라면, pageinit은 모든 위젯의 초기화가 완료된 후에 호출되는 것 같다. 정확한 '초기화 완료' 시점을 의도하는 거라면, pageinit을 사용하는 게 좋다. pageload 로드한 페이지가 DOM에 추가되고 초기화도 모두 완료된 상태에서 발생하는 이벤트. pageinit 보다 나중에 호출되는 것에 주의한다. pagebeforeshow 트랜지션을 시작하기 전에, 목적 페이지의 엘리먼트에서 발생하는 이벤트. 최초로 페이지가 로드되는 거라면, 두 번째 파라미터인 prevPage 값에 빈 배열이 할당된다. 4.jQuery Integration - Events(3/3) 50 / 74 pagebeforehide pagebeforeshow와 비슷하지만, 시작 페이지에서 발생하는 이벤트. nextPage에 대한 값을 갖는다. pageshow 트랜지션이 종료된 후에, 목적 페이지의 엘리먼트에서 발생하는 이벤트. prevPage를 갖는다.

pagechange 페이지가 로드돼서 DOM에 추가되어 초기화가 완료된 이후나, 트랜지션이 완전히 종료된 다음에 호출되는 이벤트. 트랜지션 관련 이벤트(show/hide)는 pagechange 전에 호출되는 것에 주의한다. 4.jQuery Integration - Event Sequences(1/2) 51 / 74

최초 페이지를 열었을 때

• 전체 문서(document) mobileinit -> pagebeforechange -> pagebeforecreate -> pagecreate -> pageinit -> pagebeforeshow -> pageshow -> pagechange

• 열린 문서의 페이지 엘리먼트 pagebeforecreate -> pagecreate -> pageinit -> pagebeforeshow -> pageshow 4.jQuery Integration - Event Sequences(2/2) 52 / 74

Ajax로 다른 페이지를 불러와 열었을 때

• 전체 문서(document) pagebeforechange -> pagebeforeload -> pagebeforecreate -> pagecreate -> pageinit -> pageload -> pagebeforechange -> pagebeforehide -> pagebeforeshow -> pagehide -> pageshow -> pagechange

• 열린 문서의 페이지 엘리먼트 pagebeforehide -> pagehide

• 불러온 문서의 페이지 엘리먼트 pagebeforecreate -> pagecreate -> pageinit -> pagebeforeshow -> pageshow

TEST : http://ohgyun.github.io/jqm-events-order/index.html 5.Create custom plugins for Cordova 53 / 74

What is a Cordova plugin

• Cordova is a set of command line tools and a plugin bridge for building native apps for the app stores that lets us build our app in a web view, and call native code from JavaScript.

• When we install Cordova on our computer, we’re installing a set of tools that helps package up this web content, place it into a native app container, deploy it to a device or simulator for testing, and build binaries for final release to the app store.

• Inside of that container is a relatively small bridge that transports certain JavaScript calls we make into corresponding native code to give our app the ability to do complex, native things, that aren’t baked into the standard Web APIs.

• Building Cordova plugins means we are writing some JavaScript to call down to some Native (Obj-c/Swift, Java, etc.) code we also write, and returning the result to our JavaScript.

• To sum it up: we build a Cordova plugin when we want to do something natively that doesn’t yet have a Web API analog, like accessing HealthKit data on iOS or using the Fingerprint scanner on Android. 5.Create custom plugins for Cordova 54 / 74

1. use the plugman tool to create custom plugin

2. get all mitosis on an existing plugin by cloning it

3. use a cordova plugin template 5.Create custom plugins for Cordova 55 / 74 download template from https://github.com/ionic-team/cordova-plugin-template cordova-plugin-template-master ├── LICENSE ├── README.md ├── package.json ├── plugin.xml ├── src │ ├── android │ │ └── com │ │ └── example │ │ └── MyCordovaPlugin.java │ └── ios │ ├── MyCordovaPlugin.h │ └── MyCordovaPlugin.m └── www └── plugin.js 5.Create custom plugins for Cordova 56 / 74

• plugin.xml is one of the most important files

• It’s what Cordova parses to figure out what platforms your plugin supports, preferences it has that the user can configure, source files we’ll include in our final app build, and more.

• “src” is where our native code lives. If we peek into here we see an ios and android folder.

• “www” is where the JavaScript code for our plugin lives. This is what gets called first and then kicks off Cordova to call our native code. 5.Create custom plugins for Cordova 57 / 74 hello ├── config.xml ├── hooks │ └── README.md ├── merges │ └── android ├── platforms │ ├── android │ ├── ios │ └── platforms.json ├── plugins │ ├── android.json 3 │ ├── cordova-plugin-battery-status │ ├── cordova-plugin-template cordova-plugin-template │ ├── cordova-plugin-whitelist ├── LICENSE │ ├── fetch.json 2 ├── README.md │ └── ios.json 4 ├── package.json └── www ├── plugin.xml 1 ├── css ├── src ├── images │ ├── android ├── index.html 5 │ │ └── com └── js │ │ └── example 6 │ │ └── MyCordovaPlugin.java │ └── ios │ ├── MyCordovaPlugin.h │ └── MyCordovaPlugin.m └── www └── plugin.js 5.Create plugins for Cordova - plugin.xml 58 / 74

Cordova Plugin Template MIT echo,plugin,cordova

5.Create custom plugins for Cordova 59 / 74 cordova-plugin-template/plugin.xml

Cordova Plugin Template MIT echo,plugin,cordova

• the plugin.xml file is where everything happens and it’s where we should start.

• give our plugin a unique name and id.

• As far as naming conventions go, the id is usually of the form this-is-a-plugin, like cordova-plugin-device (as an example) 5.Create plugins for Cordova - 60 / 74

5.Create plugins for Cordova - 61 / 74

5.Create plugins for Cordova - fetch.json 62 / 74

{ "cordova-plugin-whitelist": { "source": { "type": "registry", "id": "cordova-plugin-whitelist@1" }, "is_top_level": true, "variables": {} }, "cordova-plugin-battery-status": { "source": { "type": "registry", "id": "cordova-plugin-battery-status" }, "is_top_level": true, "variables": {} }, "cordova-plugin-template": { "source": { "type": "registry", "id": "cordova-plugin-template" }, "is_top_level": true, "variables": {} } } 5.Create plugins for Cordova - android.json,ios.json 63 / 74

{ "prepare_queue": { "installed": [], "uninstalled": [] }, "config_munge": { "files": {} }, "installed_plugins": { "cordova-plugin-whitelist": { "PACKAGE_NAME": "kr.co.rcube.hello" }, "cordova-plugin-battery-status": { "PACKAGE_NAME": "kr.co.rcube.hello" }, "cordova-plugin-template": { "PACKAGE_NAME": "kr.co.rcube.hello" } }, "dependent_plugins": {} } 5.Create plugins for Cordova - www/index.html 64 / 74

jQuery Mobile Demos

type="text/javascript" src="js/index.js">

5.Create plugins for Cordova - js/index.js 65 / 74 var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) {

alert("received Event:" + id);

alert(window.MyCordovaPlugin);

window.MyCordovaPlugin.getDate(function(rtn){ alert(rtn); });

console.log('Received Event: ' + id); } }; app.initialize(); 5.Create plugins for Cordova - build & emulate 66 / 74

$ cordova build $ cordova emulate android 5.Create plugins for Cordova - 67 / 74

$ cordova build $ cordova emulate ios 5.Create plugins for Cordova - status after “build”(1/2)68 / 74

android hello/www hello/platforms/android/assets/www ├── css ├── cordova-js-src │ ├── images │ ├── android │ │ └── ajax-loader.gif │ │ ├── nativeapiprovider.js │ └── jquery.mobile-1.4.5.css │ │ └── promptbasednativeapi.js ├── images │ ├── exec.js ├── index.html │ ├── platform.js └── js │ └── plugin ├── index.js │ └── android ├── jquery.js │ └── app.js └── jquery.mobile-1.4.5.js ├── cordova.js ├── cordova_plugins.js ├── css │ ├── images hello/platforms/android/src │ │ └── ajax-loader.gif ├── com │ └── jquery.mobile-1.4.5.css │ └── example ├── images │ └── MyCordovaPlugin.java ├── index.html ├── kr ├── js │ └── co │ ├── index.js │ └── rcube │ ├── jquery.js │ └── hello │ └── jquery.mobile-1.4.5.js │ └── MainActivity.java └── plugins └── org ├── cordova-plugin-battery-status └── apache │ └── www └── cordova │ └── battery.js ├── batterystatus └── cordova-plugin-template │ └── BatteryListener.java └── www └── whitelist └── plugin.js └── WhitelistPlugin.java 5.Create plugins for Cordova - status after “build”(2/2)69 / 74

ios

hello/www hello/platforms/android/assets/www ├── css ├── cordova-js-src │ ├── images │ ├── exec.js │ │ └── ajax-loader.gif │ └── platform.js │ └── jquery.mobile-1.4.5.css ├── cordova.js ├── images ├── cordova_plugins.js ├── index.html ├── css └── js │ ├── images ├── index.js │ │ └── ajax-loader.gif ├── jquery.js │ └── jquery.mobile-1.4.5.css └── jquery.mobile-1.4.5.js ├── images ├── index.html ├── js │ ├── index.js │ ├── jquery.js hello/platforms/ios/HelloWorld/Plugins │ └── jquery.mobile-1.4.5.js ├── README └── plugins ├── cordova-plugin-battery-status ├── cordova-plugin-battery-status │ ├── CDVBattery.h │ └── www │ └── CDVBattery.m │ └── battery.js └── cordova-plugin-template └── cordova-plugin-template ├── MyCordovaPlugin.h └── www └── plugin.js └── MyCordovaPlugin.m 5.Create plugins for Cordova - calling native methods70 / 74 hello/plugins/cordova-plugin-template/www var exec = require('cordova/exec'); var PLUGIN_NAME = 'MyCordovaPlugin'; var MyCordovaPlugin = { echo: function(phrase, cb) { exec(cb, null, PLUGIN_NAME, 'echo', [phrase]); }, getDate: function(cb) { exec(cb, null, PLUGIN_NAME, 'getDate', []); } }; module.exports = MyCordovaPlugin;

javascript snippet in Web Page window.MyCordovaPlugin.getDate(function(rtn){ alert(rtn); }); 5.Create plugins for Cordova - calling native methods 71 / 74 package com.example; import org.apache.cordova.CallbackContext; hello/plugins/cordova-plugin- import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; template/src/android/com/ import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; example/MyCordovaPlugin.java import org.apache.cordova.PluginResult.Status; import org.json.JSONObject; import org.json.JSONArray; import org.json.JSONException; import android.util.Log; import java.util.Date; public class MyCordovaPlugin extends CordovaPlugin { private static final String TAG = "MyCordovaPlugin";

public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView);

Log.d(TAG, "Initializing MyCordovaPlugin"); }

public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { if(action.equals("echo")) { String phrase = args.getString(0); // Echo back the first argument Log.d(TAG, phrase); } else if(action.equals("getDate")) { // An example of returning data back to the web layer final PluginResult result = new PluginResult(PluginResult.Status.OK, (new Date()).toString()); callbackContext.sendPluginResult(result); } return true; }

} 5.Create plugins for Cordova - calling native methods 72 / 74 hello/plugins/cordova-plugin-template/src/ios/MyCordovaPlugin.h #import @interface MyCordovaPlugin : CDVPlugin { } // The hooks for our plugin commands - (void)echo:(CDVInvokedUrlCommand *)command; - (void)getDate:(CDVInvokedUrlCommand *)command; @end hello/plugins/cordova-plugin-template/src/ios/MyCordovaPlugin.m #import "MyCordovaPlugin.h" #import @implementation MyCordovaPlugin - (void)pluginInitialize { } - (void)echo:(CDVInvokedUrlCommand *)command { NSString* phrase = [command.arguments objectAtIndex:0]; NSLog(@"%@", phrase); } - (void)getDate:(CDVInvokedUrlCommand *)command { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; [dateFormatter setLocale:enUSPOSIXLocale]; [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"]; NSDate *now = [NSDate date]; NSString *iso8601String = [dateFormatter stringFromDate:now]; CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:iso8601String]; [self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; } @end 5.Create plugins for Cordova - 73 / 74 hello ├── config.xml ├── hooks │ └── README.md ├── merges │ └── android ├── platforms │ ├── android │ ├── ios │ └── platforms.json ├── plugins │ ├── android.json 3 │ ├── cordova-plugin-battery-status │ ├── cordova-plugin-template cordova-plugin-template │ ├── cordova-plugin-whitelist ├── LICENSE │ ├── fetch.json 2 ├── README.md │ └── ios.json 4 ├── package.json └── www ├── plugin.xml 1 ├── css ├── src ├── images │ ├── android ├── index.html │ │ └── com └── js │ │ └── example 5 │ │ └── MyCordovaPlugin.java │ └── ios │ ├── MyCordovaPlugin.h 6 │ └── MyCordovaPlugin.m └── www └── plugin.js 74 / 74

Q & A