Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Unit 1:
Unit 1: Introducing the Course
Choose a Framework
Intel XDK NEW integrates an easy-to-use, drag & drop app designer
with Brackets, a highly-regarded, open-source editor with syntax helpers
and auto-completion.
Use the built-in Apache Ripple device emulator to simulate your app
running on multiple devices, from different geographic locations, varying
bandwidth conditions, and changing orientations. Use the integrated
Google Chrome Dev Tools to troubleshoot runtime issues.
By loading Intel App Preview onto your mobile devices, you'll be able to
easily:
Run your app on physical devices without rebuilding
Debug your app while it's running on the device, using the integrated
weinre remote debugger.
Conduct performance profiling
Check out demo apps.
Intel App Preview is available for iOS, Android, and Windows Phone.
Figure 5: Test your app on physical devices with Intel App Preview
After you've completed your testing, use Intel XDK's integrated Apache
Cordova framework to build native apps for all the popular mobile
platforms.
The Intel XDK API that includes features not currently available in
Cordova, including:
Facebook login API
Android multi-touch
Oauth support
Enhanced audio
Accelerated canvas
In addition, you can quickly add cloud-based features from appMobi to
such as push notification support, user management, e-commerce, and
cloud hosting.
Required Software
The following software is REQUIRED to be installed on your computer:
Intel XDK
http://xdk-software.intel.com/
Fast Track to Intel XDK student files
http://www.xdktraining.com/student.zip
Reviews test how well you remember the concepts from the unit.
You will build the Friends with Beer mobile application during your
instructor-led walkthroughs in the following order:
About Friends with Beer (Home Page)
Beer List
Friends with Beer Contact List
Friends with Beer Contact Data Entry Form
Friends with Beer Contact Detail
Friends with Beer Video
The Friends with Beer Home Page The Beers List displays a list of
contains simple html markup. It's beers that were downloaded from a
designed to help you get comfortable REST-based web service and
using the Intel XDK visual designer. cached into an HTML5 WebSQL
database.
The Contact List is driven from data The Contact form enables you to
stored in a WebSQL database. Clicking edit information about your
on the button in the top-left corner contacts. It also converts their
enables you to import data from your street address to a lat/lng position
phone's native contacts app. Users can on-the-fly and has client-side data
actually shake the device to select a validation.
friend at random.
The Friends with Beer Detail Page The Video page displays a
enables the user to activate the device's streaming video from Vimeo and
phone dialer, email application, and an mp4 from a web server so that
navigation app. It also uses Google the user will never have to feel like
Maps to display real-time traffic they're drinking alone.
conditions around your friend's
location.
Steps
OS/X Users:
3. Open the downloaded .dmg file
4. Double-click on the .pkg file
5. Complete the steps in the installation wizard.
6. Select Go > Applications and verify that XDK New is present.
End of Walkthrough --
Unit Summary
The course is presented through a combination of lectures and hands-
on exercises.
The course has been designed assuming that you already understand
HTML, CSS, and some Javascript.
The course consists of 10 units that cover the essentials of developing
mobile apps with Intel XDK New.
The course focuses on developing web and native applications for
mobile devices.
You will build a web application to keep track of your friends with
beer.
Unit Objectives
After completing this unit, you should be able to:
Understand the features and capabilities of Intel XDK New
Use the visual designer to create a Hello World page in your app.
Use the code editor to add JavaScript to your app.
Test your app on the simulator and your mobile device.
Package your app as a native application for distribution on App stores.
Unit Topics
Introducing Intel XDK New
Debugging Your Apps
Getting Help
2-1
2-2
2013 Intel Corporation.
Getting Started with Intel XDK New
Intel XDK New is organized around the sequence that HTML app
developers follow when they create and package an application:
1. Develop
Use the visual designer to prototype your graphical user interface and
handle user interactions by hand-coding javascript with the built-in
Brackets editor.
2. Emulate
Validate that your application looks and functions properly across
multiple screen resolutions, under varying bandwidth conditions, and
from different geographic locations by using the embedded Apache
Ripple emulator. Debug application errors with the integrated Google
debugger.
3. Test
Verify that your app performs as expected by running from Intel's App
Preview container. Debug the app and chart its performance as it runs
on your device by using the embedded weinre remote debugger.
4. Build
Package the app for distribution via app stores or the web using the
integrated Apache Cordova toolkit. Test device-specific features.
5. Services
Integrate cloud-based services into your app from appMobi, including
push-notifications, e-commerce, live updates, in-app purchasing, and
hosting.
2-3
2013 Intel Corporation.
Fast Track to Intel XDK New
Designing Apps
2-4
2013 Intel Corporation.
Getting Started with Intel XDK New
Developing Apps
As illustrated in Figure 3, clicking on the Emulate tab runs your app in the
Apache Ripple emulator.
The emulator enables you to simulate your app running on multiple devices
under varying environmental conditions:
2-5
2013 Intel Corporation.
Fast Track to Intel XDK New
2-6
2013 Intel Corporation.
Getting Started with Intel XDK New
The Test module, depicted in Figure 5, enables you to easily upload your
application to a testing server. You can then launch it on any device that's
running the Intel App Preview mobile application.
Figure 5: Upload your app and test it on devices using Intel App Preview
2-7
2013 Intel Corporation.
Fast Track to Intel XDK New
Figure 7: Intel XDK uses Apache Cordova to convert your web app into
native apps for all popular platforms.
2-8
2013 Intel Corporation.
Getting Started with Intel XDK New
You can also have XDK New create a distribution package for deployment
across the following web platforms:
WebApp
Enables you to post your code on a local or remote web server, or host
in AppMobi. (Your code may be downloaded as a .zip file)
Chrome
Packages your app for distribution in the Google Chrome store.
Facebook
Packages your app for distribution via the Facebook social network.
2-9
2013 Intel Corporation.
Fast Track to Intel XDK New
While you are not obligated to use appMobi, it is a convenient resource for
providing the following application support resources:
HostMobi can host your app in a PHP, .NET, or Node.js server
environment. Edge-cached hosting delivers the best performance for
on-the-go web apps, and hostMobi provides that through our
partnership with Amazon's Elastic Computing Cloud, (which now
spans the entire globe).
Live Update enables you to notify users that a new version of your
app is available. You have the option to push app updates immediately
instead of waiting for your users to upgrade at their leisure.
Storeview is a cloud-based reporting service that aggregates detailed
app analytics from the most popular app stores and displays them in an
interactive dashboard.
Pushmobi enables you to send push notifications to your subscribers.
You can target messages to a particular user target users based on
search filters.
1Touch is an in-app purchase (IAP) cloud service, that allows you to
interface with various app stores using a single line of javascript.
1Touch takes away the pain of integrating with the various app stores
and payment providers. With a single function call you can sell in-app
items on IOS, Android, Windows8, Windows8 Phone, Facebook and
the Chrome Store.
2 - 10
2013 Intel Corporation.
Getting Started with Intel XDK New
Steps
Design a Page
11. From the Controls panel, drag a Header and drop it onto the design
canvas.
12. In the Header Settings panel, turn on the checkbox adjacent to the Title
property and enter the following title:
Friends with Beer
2 - 11
2013 Intel Corporation.
Fast Track to Intel XDK New
15. In the Text Settings panel, change the text to the following:
Welcome to Friends with Beer!
2 - 12
2013 Intel Corporation.
Getting Started with Intel XDK New
2 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
Label Description
Sources Displays all of the JavaScript files that were loaded into the
browser as part of the request. You can set breakpoints and
step through your code one line at a time. You can also
define watch expressions to keep an eye on the contents of
your variables.
Timeline Displays the time to download files from the server, the
time to execute scripts, and the time to render the output.
Use the timeline to develop insights into where your
bottlenecks might be in your code as well as benchmark
your changes.
2 - 14
2013 Intel Corporation.
Getting Started with Intel XDK New
As depicted in Figure
13, you can use the
debugger controls to
interactively step
through your code.
You can also set watch
expressions in order to
view how your code
changes the contents of
your variables.
2 - 15
2013 Intel Corporation.
Fast Track to Intel XDK New
Figure 14: Variables that are output via console.log appear in the Chromium
debugger Console view
The Chromium debugger can do far more than just report errors and output
the results of console.log() statements. You can actually use it to interact
with your application in real-time, use it to experiment with invoking
javascript api methods, and change the contents of variables on-the-fly.
As depicted in figure 15, you can even fire events on application elements
and see the result in the emulator!
Figure 15: Invoking application methods from the Chromium console view.
2 - 16
2013 Intel Corporation.
Getting Started with Intel XDK New
If your application invokes methods from the Cordova API, or uses device
features that are not natively supported by Javascript, you may find
yourself in a situation when it's most effective to troubleshoot the app when
it's actually running on a physical device.
Using a desktop debugger to inspect an app running on a device is a
process called remote debugging. Remote debugging is supported by the
Intel XDK via the weinre remote debugger.
Figure 16: Add the <script> from the Test tab onto all html pages that you
need to remotely debug.
2 - 17
2013 Intel Corporation.
Fast Track to Intel XDK New
As depicted in figure 17, after you click the Begin Debugging on Device
button, the weinre extension for the Chromium browser appears, enabling
you to troubleshoot your app as it's runs on your device. The debugger
functions nearly identically to the one that you used in the Emulate panel.
2 - 18
2013 Intel Corporation.
Getting Started with Intel XDK New
Steps
Open a Project
1. Open Intel XDK New
2. Click on the word PROJECTS in the top-left corner of the GUI.
3. Click the Open a Project button.
4. Select the following file:
/ftIntelXdkNew/walk/walk2_2/walk2_2.xdk
10. After the code that you inserted from the prior step, insert a for loop
that loops from 0 to 4:
for (var i=0; i<5; i++) {
11. Inside the for loop, insert a statement that outputs the value of the
variable i to the debugging console:
console.log(i);
12. Select File > Save from the code editor's menu.
2 - 19
2013 Intel Corporation.
Fast Track to Intel XDK New
2 - 20
2013 Intel Corporation.
Getting Started with Intel XDK New
39. Note that the console output from your mobile app running on your
device appears in the weinre remote debugger console view.
40. Click on the End Debugging Button to end your remote debugging
session.
End of Walkthrough --
2 - 21
2013 Intel Corporation.
Fast Track to Intel XDK New
Getting Help
Intel XDK New ships with online documentation and sample applications,
and has community support resources available as well. As illustrated by
Figure 19, help features are available by clicking on the yellow question
mark button.
Selecting the Visit the Help Page link opens your web browser to the Intel
Developer Zone at http://software.intel.com/en-us/html5/articles/xdkdocs.
From here, you can get quick access to Intel's App Framework docs, the
Apache Cordova API docs, jQuery API, and Google Chrome Dev Tools
docs
2 - 22
2013 Intel Corporation.
Getting Started with Intel XDK New
Perhaps the most relevant documentation for this course is the Intel XDK
API documentation, which contains information about available javaScript
methods in the intel.xdk namespace. You can access these resources
directly from:
http://www.html5dev-software.intel.com/documentation/jsAPI/index.html
This package documents methods that enable you to access the following
resources:
Mobile device physical resources, including the camera and
accelerometer
Facebook API support
Supporting multitouch on Android devices
oAuth authentication methods
Interacting with the accelerated Canvas App Game interface plugin
2 - 23
2013 Intel Corporation.
Fast Track to Intel XDK New
The Intel XDK New developer forum, depicted in Figure 22, is a great
resource for interfacing with other developers and the Intel XDK
development team. Post your technical support questions here and receive
quick responses from other developers as well as members of Intel's XDK
New development team.
2 - 24
2013 Intel Corporation.
Getting Started with Intel XDK New
As depicted in Figure 23, Intel XDK New ships with 14 separate sample
applications that aptly demonstrate how to use commonly requested mobile
app features. Documentation for each example, accessed by pressing the
document button, highlights the specific API calls that were critical in
producing the desired outcome.
Name Description
2 - 25
2013 Intel Corporation.
Fast Track to Intel XDK New
Name Description
Hello World The classic. You know it, you love it.
IQM List A JQM-based app that uses the Rotten Tomatoes API to
View create a paginated list of DVD rentals. It demonstrates
how to populate a list view with live data and
dynamically generate pages.
2 - 26
2013 Intel Corporation.
Getting Started with Intel XDK New
Steps
2 - 27
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Summary
Designing and developing applications for handheld devices is a
completely different process than writing for desktop browsers
Intel XDK New is an integrated development environment for creating
mobile applications built on web standards HTML 5, JavaScript, and
CSS3.
Intel XDK New integrates many best-of-breed HTML5 development
tools including the following:
2 - 28
2013 Intel Corporation.
Getting Started with Intel XDK New
Unit Review
1. Do you need to install any software other than Intel XDK New in order
to develop, test, build, and deploy a mobile app?
3. Which physical device features can you test with the Emulator?
2 - 29
2013 Intel Corporation.
(This page intentionally left blank)
Unit 3:
Page Layout
Unit Objectives
After completing this unit, you should be able to:
Define logical pages in your application
Use layout controls to position elements on a page
Implement your app's navigational controls
Enable animated transitions between pages
Add text and image content to your application
Unit Topics
Defining Pages
Adding Content
3-1
Defining Pages
jQuery mobile uses a combination of HTML tags and HTML5 custom data
properties to implement a page-based architecture for layout. An HTML
file may contain either a single page widget, or multiple page widgets.
Pages are typically indicated by <div> tags with a data-role property equal
to page. Most jQuery Mobile pages, therefore use the the following
structure:
<div data-role="page" id="page1">
</div>
Note: The Intel XDK New visual wysiwyg designer does not support
defining multiple pages within a single .html file.
Attribute Description
});
3-2
2013 Intel Corporation.
Page Layout
3-3
2013 Intel Corporation.
Fast Track to Intel XDK New
The page header typically displays a page title and can display up to two
buttons which are aligned to the left and right of the title, respectively.
Headers are usually placed in a fixed position at either the top or bottom of
a page.
The title text is normally an H1 heading element but it's possible to use any
heading level (H1-H6) to allow for semantic flexibility.
The basic syntax for implementing a header or resembles the following:
<div data-role="page" id="page1">
</div>
The header container automatically sets the first child link to the left button
slot and the second child link in the right as depicted by the following
example:
<div data-role="header">
<a href="#" data-icon="delete">Cancel</a>
<h1>Edit Contact</h1>
<a href="#" data-icon="check">Save</a>
</div>
You can also set button position by applying the ui-btn-right and ui-btn-left
style classes. This is particularly useful if you need to place a single button
on the right of a header as illustrated by the following example:
<div data-role="header">
<h1>Edit Contact</h1>
<a id="btnSave"
data-icon="check"
class="ui-btn-right">Save</a>
</div>
3-4
2013 Intel Corporation.
Page Layout
<div data-role="header"
data-position="fixed">
<a data-rel="back"
data-role="button"
data-icon="back">Back</a>
<button
id="btnSaveFriend"
data-icon="save"
class="ui-btn-right">Save</a>
</div>
</div>
3-5
2013 Intel Corporation.
Fast Track to Intel XDK New
<div data-role="footer">
<div data-role="navbar">
<ul>
<li><a href="#">About</a></li>
<li><a href="#">Contacts</a></li>
<li><a href="#">Beers</a></li>
<li><a href="#">Drink!</a></li>
</ul>
</div>
</div>
3-6
2013 Intel Corporation.
Page Layout
<div data-role="footer">
<div data-role="navbar">
<ul>
<li><a
href="index.html"
class="ui-btn-active ui-state-persist"
>About</a>
</li>
<li><a href="contacts.html"
data-transition="slide">Contacts</a></li>
<li><a href="beers.html"
data-transition="fade">Beers</a></li>
<li><a href="drink.html"
data-transition="none">Drink!</a></li>
</ul>
</div>
</div>
3-7
2013 Intel Corporation.
Fast Track to Intel XDK New
You can set the buttons to display horizontally by adding the data-
type=horizontal attribute to the controlgroup container as illustrated
below:
Property Description
3-8
2013 Intel Corporation.
Page Layout
Defining Buttons
Buttons are coded with standard HTML anchor and input elements, then
enhanced by jQuery Mobile to make them more attractive and useable on a
mobile device. You'll typically use anchor links to define navigation
buttons, reserving input or button elements for form submission.
As previously described, the basic syntax for defining a button is the
following:
You can add icons to buttons by applying the data-icon property to the
anchor tag as illustrated below:
<a
href="index.html"
data-role="button"
data-icon="home">Home</a>
Icons may be positioned at the top, left, bottom, or right of the button's text
by setting the data-iconpos property:
<a
href="index.html"
data-role="button"
data-icon="home"
data-icon-pos="top">Home</a>
You can change the button's theme, causing it to display with either a light
background and dark text or a dark background and light text by applying
the data-theme property:
<a
href="index.html"
data-role="button"
data-theme="b"
>Home</a>
3-9
2013 Intel Corporation.
Fast Track to Intel XDK New
3 - 10
2013 Intel Corporation.
Page Layout
Figure 9: During this lab, you'll Implement tab-style navigation and create
placeholder pages.
Steps
Open a Project
1. Open Intel XDK New
2. Click on the word PROJECTS in the top-left corner of the GUI.
3. Click the Open a Project button.
4. Select the following file:
/ftIntelXdkNew/walk/walk3_1/walk3_1.xdk
3 - 11
2013 Intel Corporation.
Fast Track to Intel XDK New
Label : Home
Theme: (b) dark
Icon: home
Icon position: top
11. Click on the button adjacent to the Home button and configure the
following properties:
Label : Friends
Icon: user
Icon position: top
12. Click on the button adjacent to the Friends button and configure the
following properties:
Label : Beers
Icon: heart
Icon position: top
13. Drag an additional button from the Controls > Form panel and drop it
to the far right of the controlgroup in the footer.
14. Configure the following properties:
Label : Drink!
Icon: video
Icon position: top
15. Go to Code view and add the following attributes to the Home
button:
href : index.html
data-transition: slide
16. Add the following attributes to the Friends button:
href: friends.html
data-transition: slide
17. Add the following attributes to the Beers button:
href: beers.html
data-transition: slide
18. Add the following attributes to the Drink button:
href: drink.html
data-transition: fade
19. Save the file.
3 - 12
2013 Intel Corporation.
Page Layout
20. Click on the Emulate tab. The footer should appear similar to Figure
10 .
24. When prompted, select the jQuery Mobile framework and click
Select.
25. Return to the index.html file
26. Enter Code View
27. Copy the contents of the entire page to your clipboard
28. Return to friends.html
29. Enter Code view
30. Paste the contents of your clipboard into the friends.html file.
31. Cut the following code to your clipboard and paste it into the anchor
tag that points to contacts.html:
data-theme="b"
beers.html
drink.html
37. Click the Emulate tab.
3 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
38. Confirm that you can navigate between the pages by clicking/tapping
on the footer's navigation bar.
End of Walkthrough
3 - 14
2013 Intel Corporation.
Page Layout
Adding Content
You'll typically implement the page content area as a <div> tag with the
attribute data-role="content", placing it between the page header and
footer as illustrated below:
<div data-role="content">
Hello World
</div>
</div>
Figure 11: Drag and dropping rows and columns into the content area
Note that as you drag widgets from the Controls pallette, valid drop targets
become highlighted with a cyan colored background in the design canvas.
When you hover over a valid drop target, its color changes to orange.
3 - 15
2013 Intel Corporation.
Fast Track to Intel XDK New
<span class="uib_shim"></span>
</div>
3 - 16
2013 Intel Corporation.
Page Layout
Adding Text
As depicted in Figure 12, you can add text to page by dragging and
dropping the Text widget from the Controls-Media panel and dropping it
onto the design canvas.
The Text Settings panel enables you to perform the following functions:
Replace the Lorum ipsum placeholder text
Set the id property of the generated <div> element.
Set display and visibility properties
Define CSS Styles for text and margins
Create define media queries that apply styles based on screen
resolution (covered in unit 9)
3 - 17
2013 Intel Corporation.
Fast Track to Intel XDK New
Adding Images
3 - 18
2013 Intel Corporation.
Page Layout
Steps
Open a Project
1. Open Intel XDK New
2. Click on the word PROJECTS in the top-
left corner of the GUI.
Figure 15: Your goal
3. Click the Open a Project button.
4. Select the following file:
/ftIntelXdkNew/walk/walk3_2/walk3_2.xdk
Add Text
6. From the Controls > Media panel, drag a Text widget and drop it onto
the design canvas, placing it between the header and footer.
7. Open walk3_2/resources/homepagetext.txt in Code view.
8. Copy the contents of the first paragraph of homepagetext.txt to your
clipboard.
9. Open index.html in Design view.
10. In the Design canvas, click on the Text widget.
11. In the Text Settings panel, paste the contents of your clipboard into the
Text field.
Font-Size: 0.9em
Font-Family: sans-serif
Line-Height: normal
3 - 19
2013 Intel Corporation.
Fast Track to Intel XDK New
Add an Image
15. From the Controls > Media panel, drag an IMG widget and drop it
underneath the Text block on the Design Canvas.
16. Configure the following IMG settings:
Src: Resources/Beer.jpg
Alt: Beer: The cause and solution to all of our problems
End of Walkthrough --
3 - 20
2013 Intel Corporation.
Page Layout
Unit Summary
jQuery mobile uses a combination of HTML tags and HTML5 custom
data properties to implement a page-based architecture for layout.
jQuery mobile behaviors are typically defined by adding custom data
properties to html elements.
When pages are created in the mobile browser's DOM, the
pagecreate event is fired.
Every html page in your app must be linked to a mobile JavaScript
framework.
Page headers and footers can be docked into a fixed position.
JQM can automatically add a back button on a header.
Use the ButtonGroup widget to easily add navigation to your apps.
JQM supports slide and fade transitions between pages.
Buttons may be styled with icons and themes.
The Intel XDK App Designer enables you to lay out your pages using a
rows/column metaphor.
Style classes that are defined for an element can be applied to other
elements within your app.
The App Designer will automatically locate all images that have been
placed within your project folder.
3 - 21
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Review
1. Pages do not need to be linked to a mobile javascript framework
(true/false)
3 - 22
2013 Intel Corporation.
Unit 4:
Working with Data
Unit Objectives
After completing this unit, you should be able to:
Use jQuery Mobile to make asynchronous data requests
Output structured data into a ListView
Transfer data read from an application server into an HTML5 Local
SQL Database
Read data from the device's Contacts list
Unit Topics
Making External Data Requests
Working with the ListView
Caching Data in a Local Database
Importing Data from the Contacts List
4-1
You can make AJAX requests to a server using the $.ajax() method
illustrated below. $.ajax() should be used whenever you need to retrieve
external data that's not in JSON format or if you need to POST data to a
server.
$.ajax({
url: 'myservice.cfc?method=getdata',
type: 'GET',
dataType: 'json',
error : function (){ alert('there was an error'); },
success: function (data) {
console.log(data);
// debugger;
}
});
4-2
2013 Intel Corporation.
Working with Data
You can make cross-domain JSON-P requests from jQuery using the
$getJSON method illustrated below:
var url='http://someurl/someAppServerService.php?';
$.getJSON(url + 'method=somemethod&callback=?',
function(data) {
console.log(data);
}
);
Note that the ? Used in the callback url is replaced at runtime by a jQuery
with a randomly generated set of numbers. JSONP GET requests
therefore typically resemble the following:
Use $.getJSON() whenever you need to retrieve JSON data from a remote
domain that does not support CORS.
4-3
2013 Intel Corporation.
Fast Track to Intel XDK New
One of the challenges that you will have with building larger, more
complicated JQM apps is minimizing the amount of memory that your app
consumes. One strategy for managing memory is to not load data until it is
absolutely needed. For instance, if a data request is required to populate a
list view, you might want to defer making the request until such time as the
page is requested by the user.
The typical pattern to trigger the execution of code on page visibility is the
following:
$(document).bind('pageinit', function() {
$(document).on( "pagechange", function(event,page) {
switch(page.toPage[0].id) {
case 'page1' :
// initialize page 1
break;
case 'page2' :
// initialize page 2
break;
};
});
});
In the preceding code snippet, the pageinit event is triggered once the
index.html page has completed loading in the browser. In jQuery Mobile,
listening for pageinit event should be used in lieu of document.onready().
The pagechange event is triggered whenever an anchor tag is activated by
a user, causing jQM to intercept the request and load the requested html
page. You can parse the second argument returned to the pagechange event
handler to determine the id property contained within the div tag
containing the data-role=page attribute as illustrated below:
4-4
2013 Intel Corporation.
Working with Data
As your application grows in size, you may find it useful to bundle all of a
page's event listeners into a single Javascript object. This approach has
several benefits:
Encapsulation
Protected variable scoping
Code Reuse
The general approach to implement this coding style is to define a global
javascript object in your index.html file for each page of your app. For
example, you might define a Javascript object container for your beers-
page related subroutines as illustrated by the following:
var BeersPage = {
};
Inside of the JavaScript object, you'll place all of the page's dynamic
properties and methods:
var BeersPage = {
initialized: false,
init: function() {
this.initialized = true;
}
}
Note that in the preceding case, the init() method refers to the initialized
variable using the this scope as both the init() method and the initialized
property are both members of the same object.
You could then invoke the init() method for beersPage through the
following syntax:
BeersPage.init();
4-5
2013 Intel Corporation.
Fast Track to Intel XDK New
initialized: false,
data : null,
init: function() {
var me = this; // use closure to retain scope
if (me.data === null && !me.initialized) {
me.initialized = true;
var url= "http://xdktraining.com/ftxdknew/data/beer.cfc";
$.getJSON(url + "?method=getBeerList&callback=?",
function(data) {
me.data = data;
}
);
}
}
}
4-6
2013 Intel Corporation.
Working with Data
Steps
</script>
8. Inside the <script>, listen for the pageinit event to be triggered by the
index page:
});
</script>
4-7
2013 Intel Corporation.
Fast Track to Intel XDK New
9. Inside the event handler function, define a variable named page that
retrieves the file name of the current url. Your code should resemble
the following:
var page = event.target.baseURI.split('/');
page = page[page.length - 1];
10. After the code that you inserted from the prior step, check for the
existence of the global variable App.initialized. If the variable has bot
been defined, set it equal to true and call a method named App.init()
which you will define later in this exercise.
$(document).bind('pageinit', function(event,obj) {
if (!App.initialized) {
App.initialized = true;
App.init();
}
}
11. After the code that you inserted from the prior step, insert a switch/case
statement that evaluates the contents of the page variable and checks it
against each of your application's pages.
switch (page) {
case 'index.html' :
break;
case 'beers.html' :
break;
case 'friends.html' :
break;
case 'drink.html' :
break;
}
initialized: false
beers: null
13. Verify that your code appears as follows:
var App = {
initialized: false,
beers: null
}
4-8
2013 Intel Corporation.
Working with Data
initialized: false,
beers: null,
init: function() {
},
cacheBeers: function() {
}
}
15. Invoke the cacheBeers() method from the init() method as illustrated
below:
var App = {
initialized: false,
beers: null,
init: function() {
this.cacheBeers();
},
cacheBeers: function() {
}
}
17. Immediately after the code that you inserted from the prior step, make
a JSON-P request to the following URL, placing the result in the Beers
class data property and dumping its results to the debugging console.
http://xdktraining.com/ftxdknew/data/beer.cfc?
method=getBeerList&callback=?
4-9
2013 Intel Corporation.
Fast Track to Intel XDK New
22. Type the following code in the debugger's console view to output the
list of Beers:
App.beers
--End of Walkthrough--
4 - 10
2013 Intel Corporation.
Working with Data
Grouping Lists
<ul
data-role="listview"
data-autodividers="true">
<li><h3>Drucker, Aidan</h3></li>
<li><h3>Drucker, Dylan</h3></li>
<li><h3>Drucker, Steve</h3></li>
<li><h3>Gallerizzo, David</h3>
</li>
</ul>
Figure 4: Using autodividers
4 - 11
2013 Intel Corporation.
Fast Track to Intel XDK New
Script:
$("#personsList").listview({
autodividers: true,
autodividersSelector: function(li) {
return li.attr("data-lastname");
}
});
$("#personsList").listview("refresh");
In most use cases you'll need to dynamically construct a list from data that
was returned from an AJAX or JSON-P call. In order to pull this off, you'll
usually need to perform the following tasks:
Dynamically sort the array returned from the AJAX/JSON-P call.
Construct a template for generating list item markup.
Generating html markup for each item and append to the ListView.
Refresh the ListView.
4 - 12
2013 Intel Corporation.
Working with Data
Dynamically Sorting an Array
Constructing a Template
4 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
You can then convert the contents of the script to an HTML string using
jQuery's html() method:
var itemTemplate = $("#tplListItem").html();
Now that you've got your template in place, you can easily loop through
your dataset, appending markup to your list. Note that once you have
completed adding list items, you must programmatically refresh the list as
illustrated by the following example:
var list = $('ul#personsList');
4 - 14
2013 Intel Corporation.
Working with Data
Listen for tap events on list items by using the bind() method as illustrated
below:
$('#personsList > li').bind('tap', function(e) {
var targetValue = this.getAttribute('data-lastname');
alert("You selected the " + targetValue + " family");
});
4 - 15
2013 Intel Corporation.
Fast Track to Intel XDK New
Steps
4 - 16
2013 Intel Corporation.
Working with Data
Create the List
11. Open the Beers.html file in Design mode.
12. From the Controls > Widgets panel, drag a ListView widget and drop it
onto the design canvas between the page's header and footer.
13. In the ListView Settings panel, turn on the following checkboxes:
Filter
Auto Dividers
id
14. Enter the following id for the ListView:
beerslist
15. Save the file and test the application in the emulator. The list should
appear.
21. Clear the default list items from the list. Your code should appear
similar to the following:
list.empty();
22. After the code that you inserted from the prior step, define a variable
named beerTemplate that points to the html in the tplBeerItem element.
var beerTemplate = $("#tplBeerItem").html();
4 - 17
2013 Intel Corporation.
Fast Track to Intel XDK New
23. After the code that you inserted from the prior step, loop through the
data retrieved from the JSON-P transaction. Your code should appear
similar to the following:
26. Save the file and test the application in the emulator. You will need to
test the app by launching the index.html file and then clicking on the
Beers button in the footer. Note that the dividers are not displaying
correctly.
30. Save the file and re-test in the emulator. Your list dividers should now
contain the names of the countries from where the beers were made.
End of Walkthrough --
4 - 18
2013 Intel Corporation.
Working with Data
Method Description
Type Description
4 - 19
2013 Intel Corporation.
Fast Track to Intel XDK New
dbOpen : function() {
this.db = openDatabase('cart',
'1.0',
'Cafe Townsend Shopping Cart',
5*1024*1024
);
this.db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS cart(id
INTEGER PRIMARY KEY ASC, desc TEXT, qty INT, unitprice NUM)',
[], this.onSuccess, this.onError);
});
},
}
</script>
<body onload="Cart.dbOpen()">
Arg Description
4 - 20
2013 Intel Corporation.
Working with Data
Cart.db.transaction(function(tx) {
Attribute Description
4 - 21
2013 Intel Corporation.
Fast Track to Intel XDK New
function getData(db) {
db.transaction(function(tx) {
tx.executeSql(
'SELECT * FROM cart',
[],
function (tx, results) {
var len = results.rows.length;
for (var i = 0; i < len; i++)
{
alert(results.rows.item(i).desc);
}
});
})
}
Attribute Description
4 - 22
2013 Intel Corporation.
Working with Data
db.transaction(function(tx) {
var desc = "Roasted Tomato Soup";
var qty = "5";
var unitprice = "4.5";
tx.executeSql(
''.concat('INSERT INTO cart (id, desc, qty, unitprice)',
' VALUES (1,?,?,?)'
),
[desc,qty,unitprice],
function() {
alert('success');
},
function(tx,e) {
alert('Error code: ' + e.code + ':' + e.message);
}
);
});
4 - 23
2013 Intel Corporation.
Fast Track to Intel XDK New
You can manually validate that your data has been manipulated in the local
database by opening the Chromium debugger, clicking on the Resources
tab, and inspecting the contents of the Web SQL assets as indicated in
figure 8.
4 - 24
2013 Intel Corporation.
Working with Data
Steps
The init() method defines two local database tables - beer which
will hold a cached list of beers and friend which will store
extended contact information for your friends.
The runQuery() method executes the structured query language
(SQL) code that you pass into it, passing the results to a callback
function.
The writeRecord() method performs insert and update operations
on the specified table.
The importTable() method copies an array of objects into the
specified database table.
4 - 25
2013 Intel Corporation.
Fast Track to Intel XDK New
});
16. Inside the SQL callback function, loop through the data returned from
the sql transaction:
FriendsWithBeerDB.runQuery(sql, function(records) {
for (var i=0; i<records.length; i++) {
}
});
4 - 26
2013 Intel Corporation.
Working with Data
17. Inside the for-loop, append dynamically generated list items to the
ListView. Your code should appear as follows:
FriendsWithBeerDB.runQuery(sql, function(records) {
for (var i=0; i<records.length; i++) {
var item = records[i];
list.append(
beerTemplate.format(
item.id,
item.country,
item.name,
item.thecount
)
);
}
});
19. Save the file and test the app in the emulator. You should see the full
list of beers appear on the Beers tab.
End of Walkthrough
4 - 27
2013 Intel Corporation.
Fast Track to Intel XDK New
4 - 28
2013 Intel Corporation.
Working with Data
navigator.contacts.find(
fields,
function(contacts) {
alert(contacts.length + " records found!");
for (var i=0; i<contacts.length; i++) {
alert("Display Name = " + contacts[i].displayName);
}
},
function(err) {
alert("Import Failed");
},
options
);
4 - 29
2013 Intel Corporation.
Fast Track to Intel XDK New
You can read the following fields for each contact record:
Field Description
You would use the following syntax to output a contact's display name to
an alert box:
onSuccess: function(contacts) {
for (var i=0; i<contacts.length; i++) {
window.alert(contacts[i].displayName);
}
}
4 - 30
2013 Intel Corporation.
Working with Data
Field Description
To output a contact's first name followed by their last name, you would use
the following syntax:
onSuccess: function(contacts) {
for (var i=0; i<contacts.length; i++) {
window.alert(
''.concat(
contacts[i].name.givenName,
' ',
contacts[i].name.familyName
)
)
}
}
4 - 31
2013 Intel Corporation.
Fast Track to Intel XDK New
Property Description
4 - 32
2013 Intel Corporation.
Working with Data
Property Description
4 - 33
2013 Intel Corporation.
Fast Track to Intel XDK New
4 - 34
2013 Intel Corporation.
Working with Data
Steps
Label: Import
Icon: ui-icon-user
Icon Position: icon only
id: btnImportContacts
4 - 35
2013 Intel Corporation.
Fast Track to Intel XDK New
11. Inside the Contacts init() method, define an event listener for the tap
event on the btnImportContacts button.
init: function() {
$("#btnImportContacts").bind("tap", function(e) {
12. Inside the tap event handler, insert an if-else block that determines
whether the navigator.contacts object exists.
init: function() {
this.initialized = true;
$("#btnImportContacts").bind("tap", function(e) {
if (navigator.contacts) {
} else {
alert("Function not available");
}
}
}
13. Inside the if-block, insert a window.prompt() that asks the user for the
name of the contact that they want to import. If the user enters a
response, pass it along to the importContacts method of the Contacts
object.
init: function() {
this.initialized = true;
$("#btnImportContacts").bind("tap", function(e) {
if (navigator.contacts) {
var friendName = window.prompt(
"Enter your friend's name",
""
);
if (friendName != null) {
Contacts.importContacts(friendName);
}
} else {
alert("Function not available");
}
}
}
14. Save the file and test in the Emulator. You should see a Function not
available message when attempting to import contacts from the
emulator.
4 - 36
2013 Intel Corporation.
Working with Data
17. After the code that you inserted in the prior step, define a local variable
named options that is a new ContactFindOptions object.
var options = new ContactFindOptions();
18. Set the filter property of the options object to the value of the
argument that was passed into the function.
options.filter=friendName;
19. Set the multiple property of the options object to retrieve multiple
contact records.
options.multiple = true;
20. Define a local variable named fields that contains an array of strings
for the contact information that you need to retrieve (name, address,
phone, email):
var fields = [
"displayName",
"name",
"addresses",
"phoneNumbers",
"emails"
];
23. After the code that you inserted in the prior step, define the following
local variables:
address = null
phone = null
email = null
count = 0
friend = null
4 - 37
2013 Intel Corporation.
Fast Track to Intel XDK New
24. After the code that you inserted in the prior step, insert a for-loop to
iterate through the contacts data returned to the function.
for (var i=0; i<contacts.length; i++) {
25. Inside the for-loop, insert an if() block that checks if the contact's given
name is not undefined.
if (contacts[i].name.givenName != undefined) {
In the first object, the name should be equal to firstName and the
value property should equal the contact's given name.
In the second object, the name should be equal to lastName and
the value property should equal the contact's family name.
4 - 38
2013 Intel Corporation.
Working with Data
29. Inside the if() block, set the address variable equal to the result from
calling the Contacts.getPreferred() method, passing in the contact's
addresses.
if (contacts[i].addresses) {
address = Contacts.getPreferred(contacts[i].addresses);
}
30. Immediately after the code that you inserted in the prior step, add the
resulting street address and zipcode to the friends array as indicated
below:
if (contacts[i].addresses) {
address = Contacts.getPreferred(contacts[i].addresses);
friend.push(
{ name: "address", value: address.streetAddress}
);
friend.push(
{ name: "zipcode", value: address.postalCode}
);
}
32. Inside the if() block, push another object onto the friend array that
contains the contact's preferred phone number.
if (contacts[i].phoneNumbers) {
friend.push(
{
name: "phone",
value:
Contacts.getPreferred(contacts[i].phoneNumbers).value});
}
)
}
4 - 39
2013 Intel Corporation.
Fast Track to Intel XDK New
34. Inside the if() block, push another object containing user's preferred
email address onto the friend array.
if (contacts[i].emails) {
friend.push(
{
name: "email",
value: Contacts.getPreferred(contacts[i].emails).value});
}
)
}
FriendsWithBeerDB.writeRecord('friend',null, friend);
36. Immediately outside the for-loop in the onImport() method, output the
value from the count variable to the user in an alert box.
alert(count + " Contacts Imported");
End of Walkthrough --
4 - 40
2013 Intel Corporation.
Working with Data
Unit Summary
jQuery Mobile enables you to make external data requests to remote
services using either AJAX or JSON-P protocols.
All data requests are handled asynchronously.
Verify that data was retrieved correctly by outputting the server
response to the debugger using console.log()
Web apps will not be able to make cross-domain requests unless the
remote host supports cross-origin resource sharing (CORS)
Most data requests should be deferred until they are specifically
requested by the user.
Compartmentalize your code by attaching properties and methods to
Javascript objects.
Remote data can be cached in browser memory or persisted in html5
localStorage or WebSQL databases.
Use the ListView widget to output lists of data.
You can listen for tap events on list items and then programmatically
retrieve properties associated with the item that was tapped.
The Cordova API gives you access to hardware resources, including
the Contacts list.
Most Cordova API functionality must be tested on physical devices
and may not function properly in the emulator.
4 - 41
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Review
1. AJAX requests can only be made to the same domain that a web app is
hosted on (true/false).
4. The ListView search filter can only search for data that's visible to the
user.
7. Which hardware resources can only be accessed via the Cordova API?
4 - 42
2013 Intel Corporation.
Working with Data
Objectives
Steps
1. Open /lab/lab4/lab4.xdk
2. Open contacts.html
3. Drag a LISTVIEW widget onto the design canvas and configure its
properties.
4. Return to index.html
5. Modify the Contact's displayList() method to output data from the
WebSQL table into the LISTVIEW that you defined from step 3.
6. Modify the onImport() method to refresh the LISTVIEW after your
contacts have been imported.
End of Lab --
4 - 43
2013 Intel Corporation.
(This page intentionally left blank)
Unit 5:
Creating Input Forms
Unit Objectives
After completing this unit, you should be able to:
Create a data entry form
Pre-fill form fields with data
Populate a <select> control with data from a webservice
Validate data input
Transmit form data to an application server
Save form data to a WebSQL database.
Unit Topics
Creating Forms
Validating Form Input
Persisting Form Data
5-1
Creating Forms
Intel XDK New supports the following types of form fields:
HTML5 extends the standard textfield from HTML 4.01 by adding the
following easily deployed features:
Automatically set focus
Specify placeholder text
Validate that data was input in a specific format
Some of these capabilities are directly supported by the Intel XDK New
GUI as depicted in Figure 1. Others you will need to add using code view.
5-2
2013 Intel Corporation.
Creating Input Forms
Automatically Setting Focus
The HTML 5 autofocus attribute enables you to set focus to a specific form
field as soon as the form is rendered in your browser. In HTML 4 this
could only be accomplished by using JavaScript's focus() method.
<form>
<label for="myfield">
This field will automatically have cursor focus:
</label>
<input type="text" name="myfield" autofocus />
</form>
Placeholder text helps you make your forms more intuitive and usable by
allowing for descriptive text to be placed inside of a text field via the
placeholder attribute. Once the field has focus or has a value, the
placeholder text is removed.
<form>
<label for="lastname">Enter your last name:</label>
<input type="text"
name="lastname"
placeholder="Last Name" />
</form>
5-3
2013 Intel Corporation.
Fast Track to Intel XDK New
<form>
<input
type="tel"
name="phone"
placeholder="Tel" />
<input type="submit">
</form>
5-4
2013 Intel Corporation.
Creating Input Forms
<select name="beerid"
id="beerid">
Figure 5: A jQM Select Menu.
<option value="1">Amstel</option>
<option value="2">Budweiser</option>
<option value="3">Chimay Rouge</option>
<option value="4">Corona Extra</option>
</select>
5-5
2013 Intel Corporation.
Fast Track to Intel XDK New
// add placeholder
MySelect.append(tpl.format('','Please Select'));
5-6
2013 Intel Corporation.
Creating Input Forms
Design a form
Dynamically populate a <select> list
Implement a Back button
Respond to button taps
Steps
Icon: ui-icon-back
Icon position: icon only
id: btnBack
8. Go to Code mode.
9. Locate the anchor tag that was generated for the back button and add
the following attribute:
data-rel="back"
5-7
2013 Intel Corporation.
Fast Track to Intel XDK New
Icon: ui-icon-check
Icon Position: Icon only
id: btnSave
is Form: checked
Label: (unchecked)
Type: text
Placeholder: First Name
Name: firstName
id: firstName
17. From the Controls > Form palette, drag an Input widget and drop it
directly underneath the First Name field on the Design Canvas.
18. Configure the following properties:
Label: (unchecked)
Type: text
Placeholder: Last Name
Name: lastName
id: lastName
19. From the Controls > Form palette, drag an Input widget and drop it
directly underneath the Last Name field on the Design Canvas.
20. Configure the following properties:
Label: (unchecked)
Type: text
Placeholder: Street Address
Name: address
id: address
21. From the Controls > Form palette, drag an Input widget and drop it
directly underneath the Address field on the Design Canvas.
22. Configure the following properties:
Label: (unchecked)
5-8
2013 Intel Corporation.
Creating Input Forms
Type: number
Placeholder: Zip Code
Name: zipcode
id: zipcode
23. From the Controls > Form palette, drag an Input widget and drop it
directly underneath the Zip Code field on the Design Canvas.
24. Configure the following properties:
Label: (unchecked)
Type: email
Placeholder: you@you.com
Name: email
id: email
25. From the Controls > Form palette, drag an Input widget and drop it
directly underneath the email field on the Design Canvas.
26. Configure the following properties:
Label: (unchecked)
Type: telephone
Placeholder: Tel
Name: phone
id: phone
Label: (unchecked)
Options: Select a Beer
Name: beerId
id: beerId
29. Save the file
30. Open index.html in Code mode.
31. Where indicated by the comment, define a JavaScript object named
ContactForm.
var ContactForm = { };
init
populateBeerField
34. Review your code to ensure that it appears similar to the following:
5-9
2013 Intel Corporation.
Fast Track to Intel XDK New
var ContactForm = {
friendId: null,
init: function() {
},
populateBeerField : function() {
}
};
}
};
37. After the code that you inserted from the prior step, insert a for-loop
that loops through the beer data that's cached in the variable App.beers.
populateBeerField : function() {
var beerField = $("select#beerId");
for (var i=0; i< App.beers.length; i++) {
}
}
38. Inside the for-loop, insert code that dynamically outputs the data from
App.beers as <option> elements inside of the select widget.
populateBeerField : function() {
var beerField = $("select#beerId");
for (var i=0; i< App.beers.length; i++) {
beerField.append(
'<option value="{0}">{1}</option>'.format(
App.beers[i].id,
App.beers[i].name
)
);
}
}
39. After the for-loop, insert a statement to refresh the display of the select
widget.
beerField.selectmenu("refresh", true);
5 - 10
2013 Intel Corporation.
Creating Input Forms
42. From the Controls > Form palette, drag a button widget and drop it on
the right edge of the page header.
Icon: ui-icon-plus
Icon Position: Icon only
id: btnAdd
44. Go to Code mode and locate the generated markup for the button.
45. Add the following attributes to the anchor tag that wraps the add
button:
href=contactform.html
data-transition=flip
46. Save the file.
47. Return to index.html in Code mode.
48. In the Contacts object, at the end of the init() method, bind a tap event
handler to the Add Contact button.
$("#btnAdd").bind("tap", function(e) {
});
49. Inside the button tap callback function, set the friendId property in the
ContactForm object to null.
$("#btnAdd").bind("tap", function(e) {
ContactForm.friendId = null;
});
End of Walkthrough --
5 - 11
2013 Intel Corporation.
Fast Track to Intel XDK New
Type Description
5 - 12
2013 Intel Corporation.
Creating Input Forms
<script type="text/javascript"
src="jqm/jquery.mobile-min.js"></script>
<script type="text/javascript"
src="js/jquery.validate.js"></script>
</head>
5 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
You can require data input on a field by adding the required attribute to any
<input> field as illustrated below:
<label class="narrow-control" for="lastName"></label>
<input class="wide-control"
placeholder="Last Name"
type="text"
name="lastName"
id="lastName"
required >
You can also attach the required validation rule to a field by invoking a
form's validate() method (injected by the plugin):
$( "#myform" ).validate({
rules: {
lastName: {
required: true
}
}
});
Require that a properly formatted email address be entered into a form field
by applying the following validation rules:
<label class="narrow-control" for="email"></label>
<input class="wide-control"
placeholder="me@myemailaddress.com"
type="text"
name="useremail"
id="userEmail">
$( "#myform" ).validate({
rules: {
userEmail: {
required: true,
email: true
}
}
});
5 - 14
2013 Intel Corporation.
Creating Input Forms
You can set validation on string field length by using the rangelength
validator as illustrated below:
<label class="narrow-control" for="lastName"></label>
<input class="wide-control"
placeholder="Last Name"
type="text"
name="lastName"
id="lastName">
$( "#myform" ).validate({
rules: {
lastName: {
required: true,
rangelength: [2,20]
}
}
});
Require that input data may only contain characters in the range of 0-9 by
applying the digits rule as noted below:
<label class="narrow-control" for="zip"></label>
<input class="wide-control"
placeholder="zip code"
type="text"
name="zipcode"
id="zipcode">
$( "#myform" ).validate({
rules: {
zipcode: {
required: true,
digits: true
}
}
});
5 - 15
2013 Intel Corporation.
Fast Track to Intel XDK New
By default, error validation messages are injected into the form field's
<label> element. You can modify this behavior on a field-level basis by
specifying an errorPlacement method. The following example moves the
validation method into a parent <div> for a <select> element with an id of
beerid:
var form = $("form#contactform");
form.validate({
errorPlacement: function(error, element) {
if (element.attr("name") === "beerid") {
error.insertAfter($(element).parent());
} else {
error.insertAfter(element);
}
}
});
As illustrated in the following snippet, you can style the error message by
defining a css class on the label.error selector.
label.error {
float: left;
color: red;
padding-top: .5em;
vertical-align: top;
font-weight:bold
}
5 - 16
2013 Intel Corporation.
Creating Input Forms
Steps
5 - 17
2013 Intel Corporation.
Fast Track to Intel XDK New
11. After the code that you inserted in the prior step, invoke form.validate
and configure the following rules:
13. Inside the init() method of the ContactForm object, invoke the
initValidation() method.
var ContactForm = {
init: function() {
this.populateBeerField();
this.initValidation();
},
populateBeerField: function() {
// omitted for brevity
},
initValidation: function() {
// omitted for brevity
}
}
5 - 18
2013 Intel Corporation.
Creating Input Forms
id: btnSave
22. Save the file and test the app in the emulator. Clicking the save button
should trigger the display of the error validation messages.
5 - 19
2013 Intel Corporation.
Fast Track to Intel XDK New
25. Save the file and re-test the app in the emulator. You should see that
your error messages are now formatted.
End of Walkthrough --
5 - 20
2013 Intel Corporation.
Creating Input Forms
To programmatically set the value of an input field, invoke the field's .val()
method as illustrated below:
$("#firstName").val("Steve");
// select controls
var myselect = $("select#beerid");
myselect.selectedIndex = 1;
myselect.selectmenu("refresh");
5 - 21
2013 Intel Corporation.
Fast Track to Intel XDK New
submitForm: function() {
if (validator.numberOfInvalids() == 0) {
$.ajax({
type: "POST",
url: "http://www.xdktraining.com/savecontact.cfm",
data: form.serialize(),
success: function(data) {
alert("Record Saved");
},
error: function(XMLHttpRequest, textStatus, err){
var msg = ''.concat(
'status:', XMLHttpRequest.status, '\n',
'status text: ', XMLHttpRequest.statusText
);
alert(msg);
}
});
}
}
5 - 22
2013 Intel Corporation.
Creating Input Forms
Steps
5 - 23
2013 Intel Corporation.
Fast Track to Intel XDK New
} else {
alert("Invalid data input");
}
}
13. Inside the if() block, use the form.serializeArray() method to serialize
all of the form fields into a local variable named fields.
var fields = form.serializeArray();
14. Immediately after the code that you inserted in the last step, append the
values of the disabled lat and lng fields to the fields array.
fields[fields.length] = {
name: 'lat',
value: $('#lat').val()
};
fields[fields.length] = {
name: 'lng',
value: $('#lng').val()
};
15. Immediately after the code that you inserted in the last step, invoke the
FriendsWithBeerDB.writeRecord() method to transfer the data from
the fields variable into your webSQL database.
FriendsWithBeerDB.writeRecord(
'friend',
this.friendId,
fields,
function() {
}
);
16. Inside the writeRecord() callback function, use the alert() method to
output a message to the user and then reload the contacts.html page.
5 - 24
2013 Intel Corporation.
Creating Input Forms
18. Save the file and test the application in the emulator. You should now
be able to create new contact records!
});
20. Inside the event handler, retrieve the numeric identifier in the list item
and transfer its value to the ContactForm.friendId property.
$('#friendsList > li').bind('tap', function(e) {
ContactForm.friendId = this.getAttribute('data-value');
});
21. Immediately after the code that you inserted in the prior step,
programmatically change the page to contactform.html
$('#friendsList li').bind('tap', function(e) {
var ContactForm.friendId = this.getAttribute(
'data-value');
$.mobile.changePage('contactform.html');
});
22. Save the file and test in the emulator. Clicking on an item in the
Friends list should now transfer control to the data entry form.
5 - 25
2013 Intel Corporation.
Fast Track to Intel XDK New
24. Inside the loadRecord() method, define an if() block that evaluates
whether the value of the ContactForm.friendId property is null.
loadRecord: function() {
if (this.friendId != null) {
}
}
});
}
}
26. Inside the runQuery callback function, loop through the properties of
the first record that was returned from the database query, transferring
the values from the query result into the form.
loadRecord: function() {
if (this.friendId != null) {
var sql = "select * from friend where id = {0}";
sql.format(this.friendId);
FriendsWithBeerDB.runQuery(sql, function(records) {
var rec = records[0];
for (var i in rec) {
$("#" + i).val(rec[i]);
}
});
}
}
27. Immediately after the for-loop that you entered in the prior step, refresh
the beerId select menu.
$("#beerId").selectmenu("refresh", true);
this.initialized=true;
this.populateBeerField();
this.initValidation();
this.loadRecord();
var me = this;
$("#btnSave").bind("tap", function(e) {
me.submitForm();
});
}
5 - 26
2013 Intel Corporation.
Creating Input Forms
29. Save the file.
30. Test the application. You should now be able to edit existing contact
records.
End of Walkthrough --
5 - 27
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Summary
Intel XDK New and jQuery Mobile support all HTML5 form element
types.
jQuery Mobile replaces standard checkbox, radio button, and select
field controls with controls that have been optimized for a mobile
device.
Native HTML5 form field validation is not supported by most mobile
browsers.
You can easily adapt the jQuery Validation Plugin to work with jQuery
mobile.
The jQuery Validation Plugin supports validating basic patterns
including email address, required data input, string length, numeric
input, and more.
You can persist data in memory, transmit form information to an
application server, or store it in WebSQL or HTML5 localStorage.
5 - 28
2013 Intel Corporation.
Creating Input Forms
Unit Review
1. The name and id properties of an input field should always be identical
(true/false)
2. Which method do you invoke in order to get the value of a form field?
3. Which method do you invoke in order to set the value of a form field?
4. You must call the refresh method of a text input field after changing its
value (true/false)
5. Which method can you invoke to easily combine the values from all of
your form fields in order to transmit them to a server?
7. Describe how to populate a <select> control with options that are read
dynamically from an application server.
5 - 29
2013 Intel Corporation.
(This page intentionally left blank)
Unit 6:
Adding GEO Features
Unit Objectives
After completing this unit, you should be able to:
Load the Google API
Instantiate a map
Programmatically geocode an address from data input by the user
Programmatically center a map and understand the basic Google map
configuration options
Add overlays to a map
Unit Topics
Getting Started with Google Maps
Deploying a Simple Map
Programmatically Geocoding Addresses
Adding Overlays and Map Markers
6-1
To facilitate the integration of Google Maps into a jQM-based app, use the
Google Maps v3 plug-in for jQuery and jQM, available at
http://code.google.com/p/jquery-ui-map/.
6-2
2013 Intel Corporation.
Adding GEO Features
The free version of Google Maps v3 enables you to load the API using the
following syntax:
<!--- load maps API --->
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?
sensor=SET_TO_TRUE_OR_FALSE">
</script>
However, if you wish to track map usage or you need a larger number of
daily Page Views then utilizing the Purchased Key Version. API keys are
tied to both your Google account and the domain name from where your
application will be hosted. The process to obtain an API key can be found
at the following URL:
https://developers.google.com/maps/documentation/javascript/tutorial#api_
key
As noted in the instructions, you are allowed to use the key from any
domain, but it is strongly encouraged to restrict the usage from the
domain(s) you manage.
6-3
2013 Intel Corporation.
Fast Track to Intel XDK New
When you sign up for a paid API key, you'll be prompted to register a new
Project ID. This allows multiple Google services to be tied to a single
project/API key for tracking purposes.
Take the API key and inject it into the script tag that loads the maps API as
illustrated below:
<!--- load maps API --->
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?
key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE">
</script>
6-4
2013 Intel Corporation.
Adding GEO Features
6-5
2013 Intel Corporation.
Fast Track to Intel XDK New
The Google Maps V3 plug-in for jQuery and JQM is a very flexible, highly
customizable, lightweight (3.2kB or 3.9kB for the full) library One of its
best features is that you can populate a map from microformats, RDFa or
micro-data on your site, which can be used as a fallback if a user doesn't
have Javascript enabled.
The plug-in is well-documented and acts as an abstraction library for the
most commonly used functionality available from Google Maps. The
jQuery Google Maps plug-in documentation integrates links to Google
Maps Javascript V3 APIs, classes and methods, shortening the learning
curve for including Google Maps in a mobile web app.
The Google Maps V3 plug-in for jQuery and JQM comes with a variety of
libraries, in both full source and minified versions. Depending on your
implementation you may use one or more of these:
jquery.ui.map.js Main library file
jquery.ui.map.extensions.js Used with Geocoding
jquery.ui.map.microdata.js Used for microdata
implementations
jquery.ui.map.microformat.js Used with microformats
jquery.ui.map.overlays.js Used with shapes and KML
jquery.ui.map.rdfa.js Used with RDFa data
jquery.ui.map.services.js Used with Directions and Street view
Each of these libraries has an associated minified version for you to work
with. When implementing for JQM you will use a special minified version
of the main library file jquery.ui.map.full.min.js.
To handle the most basic of map implementations your to implement the
plug-in will look like the following:
<!--- Google Maps / JQuery Plugin --->
<script type="text/javascript"
src="ui/jquery.ui.map.full.min.js">
</script>
6-6
2013 Intel Corporation.
Adding GEO Features
You can instantiate a map into any HTML element that has a unique
identifier (typically a <div>). The map will conform to the defined size of
the container. A typical map container would resemble the following:
<div id="map_canvas"></div>
In order to style the map you will either provide in-line styles for the
<div> tag or provide some parameters for the div to constrain the size. In
this example, you could include a <style> block at the top of the file, or
place the style within a CSS file. The entry for the ID 'map_canvas' could
look like this:
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { width: 100%; height: 380px }
</style>
When implementing for mobile you will want pay particular attention to
the map canvas parameters. Depending on how the styles have been
implemented with the application you may have to push the map into a
fixed height.
Instantiating a map with the JQM Google Maps plugin typically requires
you to call a constructor named gmap() as illustrated below. Note the use
of #map_canvas which is used to point the map to our map_canvas
<div> and the use of the mapOptions variable to set some basic
parameters for the map,.
<!-- loading a Google Map using jQuery -->
<script type="text/javascript">
var mapOptions = {
'center': '38.986000000, -76.940131000',
'zoom': 15,
disableDefaultUI: false
};
$('#map_canvas').gmap({
center: mapOptions.center,
mapTypeId: google.maps.MapTypeId.SATELLITE,
zoom: mapOptions.zoom,
disableDefaultUI: mapOptions.disableDefaultUI
});
</script>
6-7
2013 Intel Corporation.
Fast Track to Intel XDK New
The Google Maps Javascript API Map class supports over 30 different
configuration properties, generally referred to as MapOptions. A full
listing can be found here:
https://developers.google.com/maps/documentation/javascript/reference#M
apOptions
At a minimum, the following options must be included when instantiating
a new Map object:
zoom (type int) max zoom value is 19
mapTypeId indicates the type of map to display
center center point on the map, in
Latitude/Longitude
$mapContainer.gmap({
center: loc,
zoom: 16, Figure 3: Partially
mapTypeId:google.maps.MapTypeId.SATELLITE rendered map.
});
setTimeout("$('#map').gmap('refresh')",500);
6-8
2013 Intel Corporation.
Adding GEO Features
One of the most important MapOptions is the the center option. This
option gives the map its starting center latitude and longitude coordinates.
You can manually geocode a starting address by going to http://geocoder.us
One of the main features of Google Maps are the different map types. In
the example below we used a MapOption called MapTypeID to name of
the map type displayed. These are defined in the Google API
documentation as follows:
ROADMAP (Default) - displays the normal, default 2D tiles of
Google Maps.
SATELLITE - displays photographic tiles.
HYBRID - displays a mix of photographic tiles and a tile layer for
prominent features (roads, city names).
TERRAIN - displays physical relief tiles for displaying elevation and
water features (mountains, rivers, etc.).
The value of the map type is case sensitive and coincides with the different
map types you can choose from the standard maps UI.
<!-- Instantiating a map using the Satellite Map type -->
$('#map_canvas').gmap({
'center': mapOptions.center,
'mapTypeId': google.maps.MapTypeId.SATELLITE,
'zoom': mapOptions.zoom,
'disableDefaultUI': mapOptions.disableDefaultUI
});
6-9
2013 Intel Corporation.
Fast Track to Intel XDK New
Another set of commonly used MapOptions are the controls. Google Maps
allows you to customize the various controls within your maps. In our
example on the previous page we set the disableDefaultUI option to false.
This enables the zoom, map type, and street view controls by default.
Other supported controls, which allow you more granularity, include the
following:
Property Description
6 - 10
2013 Intel Corporation.
Adding GEO Features
Steps
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?
sensor=true></script>
10. After the code that you inserted in the prior step, add a <script> tag
that loads the jQuery Google Map plugin.
<script type="text/javascript"
src="js/jquery.ui.map.js"></script>
6 - 11
2013 Intel Corporation.
Fast Track to Intel XDK New
13. From the Controls > Layout palette, drag a ROW widget and drop it
directly underneath the row that you inserted in the prior step.
14. Go to Code view.
15. Locate the markup that was generated for the second row widget and
add an id property with a value of map as illustrated below:
<div class="grid grid-pad urow uib_row_2 row-height-2"
data-uib="layout/row"
id="map">
20. After the code that you inserted in the previous step, use the gmap()
method to instantiate a map that's centered on the lat/lng position that
you noted from step 7.
21. Review your code to ensure that it appears similar to the following:
var ContactDetail = {
friendId: null,
gMap: null,
init: function() {
var $mapContainer = $("#map");
this.gMap = $mapContainer.gmap({
center: new google.maps.LatLng ("38.908696",
"-77.036527"),
zoom: 16
});
}
}
24. Save the file and test. Tapping on a list item should display a small
sliver map on the ContactDetail page.
6 - 12
2013 Intel Corporation.
Adding GEO Features
Adjust Map Rendering
25. Return to index.html in CODE mode.
26. At the bottom of the ContactDetail.init() method, use jQuery to set the
height of the map to be the height of the document body minus 300
pixels (to account for the header, footer, and top row).
$mapContainer.height ($("body").height() - 200);
27. Save the file and test in the Emulator. You should see a larger map,
however that still doesn't quite render correctly.
28. Return to index.html in CODE mode.
29. At the bottom of the ContactDetail.init() method, insert a setTimeout()
method that refreshes the map after 500 milliseconds.
setTimeout("$('#map').gmap('refresh')",500);
30. Save the file and test the application in the emulator.
End of Walkthrough --
6 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
In the following example illustrates Geocoding and address and storing the
resulting lat/long into a variable. The map is then centered on the specified
position.
6 - 14
2013 Intel Corporation.
Adding GEO Features
Steps
6 - 15
2013 Intel Corporation.
Fast Track to Intel XDK New
href=contactform.html
13. Save the file and test the application in your emulator.
17. Directly under the code that you inserted from the prior step, call the
geocoder.Geocode method, passing it the address and zip code that the
user entered in the form.
geoCode: function() {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address : $('#address').val() + " " + $('#zipcode').val()
}, function(results,status) {
});
}
18. Inside the geocoder callback function, insert code to populate the lat
and lng text fields with the resulting geocode data. If the geocding
failed, set the values of the lat and lng field to the empty string. Your
code should appear similar to the following:
geoCode: function() {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address : $('#address').val() + " " + $('#zipcode').val()
}, function(results,status) {
if(status != google.maps.GeocoderStatus.OK) {
alert("Address not found");
$("#lat").val('');
$("#lng").val('');
} else {
$("#lat").val(results[0].geometry.location.lat());
$("#lng").val(results[0].geometry.location.lng());
}
});
}
6 - 16
2013 Intel Corporation.
Adding GEO Features
20. Save the file and test the app in the Emulator. Editing a contact record
should cause the address to be geocoded with the results getting placed
into the lat/lng input fields.
-- End of Walkthrough --
6 - 17
2013 Intel Corporation.
Fast Track to Intel XDK New
Using Overlays
Google Maps enables you to add transparency layers to your map that
visualize the following datasets:
Layer Description
6 - 18
2013 Intel Corporation.
Adding GEO Features
$mapContainer.gmap({
center: new google.maps.LatLng ("38.908696", "-77.036527"),
zoom: 16,
callback: function(map) {
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
}
});
Loading the Panoramio layer requires you to modify the url of the <script>
tag that loads the Google Maps API as illustrated by the following
example:
<script
src="https://maps.googleapis.com/maps/api/js?
v=3.exp&sensor=true&libraries=panoramio">
</script>
With the Panoramio version of the Google Maps API loaded, it becomes a
simple matter to instantiate the map with local photos:
$mapContainer.gmap({
center: new google.maps.LatLng ("38.908696", "-77.036527"),
zoom: 16,
callback: function(map) {
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
6 - 19
2013 Intel Corporation.
Fast Track to Intel XDK New
Markers identify points on a map and inherit from the same base class as
overlays. They are assigned a position on a map, and can be assigned a
number of properties, including tooltips and custom icons for display.
Using the Google Maps plug-in for jQuery and JQM you can add a marker
to an existing map with the following block of code:
$('#map_canvas').gmap('addMarker', {
position: '42.345573,-71.098326',
bounds: false
});
In most use-cases, you'll want to place a maker on the map to identify the
center point. As illustrated by the following code snippet, you can easily
implement this in the callback handler that executes during the map
instantiation process.
var $mapContainer = $("#map");
$mapContainer.gmap({
center: new google.maps.LatLng ("38.908696", "-77.036527"),
zoom: 16,
callback: function(map) {
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
this.addMarker({
position: map.getCenter()
})
}
});
6 - 20
2013 Intel Corporation.
Adding GEO Features
Steps
}
);
6 - 21
2013 Intel Corporation.
Fast Track to Intel XDK New
9. After the code that you inserted in the prior walkthrough, set the
ContactDetail.mapCenter property equal to the a Google LatLng object
that's set to the lat/lng position retrieved from the database query.
me.mapCenter = new google.maps.LatLng (
records[0].lat, records[0].lng
);
10. Invoke the initMap() method from the WebSQL function callback.
}
});
13. Inside the callback function, instantiate the traffic and panoramio
layers and apply them to the map.
this.gMap = $mapContainer.gmap({
center: this.mapCenter,
zoom: 16,
callback: function(map) {
}
});
6 - 22
2013 Intel Corporation.
Adding GEO Features
15. Save the file and test in the emulator using a friend record that has
been successfully geocoded.
-- End of Walkthrough --
6 - 23
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Summary
There are multiple licensing options for the Google Maps Javascript
API V3, including a paid for subscription model
Use the JavaScript loader to dynamically load Google API's at runtime
To facilitate using Google Maps with jQuery and JQM you can use the
Google Maps V3 plugin for jQuery and jQuery Mobile
Use the google.maps.Map() object to instantiate maps on your pages in
basic Javascript
Use $(#map_canvas).gmap() to instantiate maps using the plugin for
jQuery mobile
Use jQuery to loop through a returned dataset to programmatically
populate a map overlay components.
Create map markers using the google.maps.Marker() or addMarker()
and assign them to overlays
6 - 24
2013 Intel Corporation.
Adding GEO Features
Unit Review
1. What do you need to get started using the Google Maps API?
4. What are the types of overlays that you can place on a Google Map?
6 - 25
2013 Intel Corporation.
(This page intentionally left blank)
Unit 7:
Using Device Features
Unit Objectives
After completing this unit, you should be able to:
Retrieving the device's current location
Programmatically activate the phone dialer
Launch the device's email client with the subject, body, and to: fields
pre-filled
Prompt the user to launch the device's built-in navigation app
Create an event listener for the accelerometer so that an action is
performed when the user shakes their device.
Listen for push notifications
Unit Topics
Retrieving the Device's Current Location
Launching the Phone, Email, and Navigation Apps
Listening to the Accelerometer
Listening for Push Notifications
7-1
function(position) {
var pos = new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude);
},
function (error) {
var msg = "";
switch(error.code) {
case error.PERMISSION_DENIED:
msg="User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
msg="Position is unavailable."
break;
case error.TIMEOUT:
msg="The GPS request timed out";
break;
case error.UNKNOWN_ERROR:
msg = "An unknown error occurred getting your position"
break;
}
alert(msg);
}
);
7-2
2013 Intel Corporation.
Using Device Features
In addition to the latitude and longitude, most device browsers will also
return the following information as properties of the position.coords object.
Property Description
You can calculate the distance between two points by using either the
Haversine formula or the Spherical Law of Cosines. The following
function represents a JavaScript implementation of the Haversine formula:
return R * c;
7-3
2013 Intel Corporation.
Fast Track to Intel XDK New
7-4
2013 Intel Corporation.
Using Device Features
Steps
7-5
2013 Intel Corporation.
Fast Track to Intel XDK New
15. After the code that you added in the prior step, define a local variable
named html that processes the contact's information through the
template.
var html = tplContact.format(
this.contactData.firstName,
this.contactData.lastName,
this.contactData.address,
this.contactData.beername
);
16. After the code that you inserted in the prior step, output the contents of
the html variable to the #contactdetails <div> element.
$("#contactdetails").html(html);
7-6
2013 Intel Corporation.
Using Device Features
22. Invoke the navigator.geolocation.getCurrentPosition() method,
defining success and error callback functions. Your code should
appear similar to the following:
navigator.geolocation.getCurrentPosition(
function(position) {
},
function(error) {
}
);
23. Inside the success callback function, convert the device's latitude and
longitude coordinates to a google maps lat/lng object and store the
resulting object into the ContactDetail.currentPosition property.
navigator.geolocation.getCurrentPosition(
function(position) {
me.currentPosition =
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
);
},
function(error) {
}
);
24. After the code that you inserted in the prior step, define a local variable
named miles that contains the calculated distance between the device
and the selected friend.
25. Immediately after the code that you inserted in the prior step, output
the value from miles into the <span id=contactdistance> element.
$("#distancetofriend").html(miles + " miles ");
26. Inside the error function callback, output an alert() that indicates that
an error occurred in retrieving the device's coordinates.
27. Where indicated by the comment inside of the ContactDetail.init()
method, invoke the outputDistance function.
28. Save the file and test. Tapping on a contact should now display the
distance between the device and the contact's address as illustrated by
the screenshot in Figure 2.
End of Walkthrough --
7-7
2013 Intel Corporation.
Fast Track to Intel XDK New
Use the tel URL scheme to launch the device's phone dialer and initiate
dialing of the specified phone number. Whether or not the user is prompted
to dial or the dialing occurs automatically is dependent on the type of
mobile operating system being used.
The javascript syntax to activate the native Phone app is:
location.href="tel:555-555-5555";
Note that the iOS browser will automatically try to detect and hyperlink
strings that match a phone number pattern. You can disable this behavior
by adding the following meta tag to your html:
<meta name = "format-detection" content = "telephone=no">
Use the mailto: url scheme to launch the mail app's compose feature and
programmatically fill the following fields:
Syntax Description
7-8
2013 Intel Corporation.
Using Device Features
// android-specific code
} else if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
On iOS, the maps URL scheme can open the native Apple maps app to
show geographical locations as well as generate driving directions between
two points.
On iOS, maps links are specified using a special maps:// uri as illustrated
by the following snippet:
Argument Description
7-9
2013 Intel Corporation.
Fast Track to Intel XDK New
Argument Description
z Zoom level
The following snippet illustrates how to generate a link that, when pressed,
would launch an iOS device's maps app with turn-by-turn directions:
var fromAddr = escape("1400 16th St NW 20036");
var toAddr = escape("2000 K St NW 20036");
var tpl='<a href="maps://?daddr={0}&saddr={1}">Click Me</a>'
location.href = tpl.format(fromAddr,toAddr);
Opening the navigation app on Android can be a little tricky since the
Android webview, which is used to drive native-apps functions slightly
differently than the native Android browser when it's running in standalone
mode.
If running your code as a web app, the browser will respond similarly to
the technique previously described for iOS devices you simply need to
specify the url for maps.google.com as illustrated below:
var fromAddr = escape("1400 16th St NW 20036");
var toAddr = escape("2000 K St NW 20036");
var tpl='<a href="http://maps.google.com/maps?
daddr={0}&saddr={1}">Click Me</a>'
location.href = tpl.format(fromAddr,toAddr);
You can also open the native Google Maps app by using the geo: uri. As
illustrated by the following use case, you can pass a latitude and longitude
as a comma-delimited list. The z argument indicates zoom level on a scale
of 1-23 where 1 is the whole earth and 23 is is the highest zoom level.
<a href="geo://?
saddr=20.544,34.34&daddr=20.866,45.345">Navigate!</a>
7 - 10
2013 Intel Corporation.
Using Device Features
Unfortunately, the Android WebView that is used to run your app in
native mode does not recognize that a maps.google.com url or the geo:
uri should be opened in an external app.
var tpl="http://maps.google.com/maps?
daddr={0}&saddr={1}";
// PhoneGap application
} else {
// Web page
7 - 11
2013 Intel Corporation.
Fast Track to Intel XDK New
Steps
Mini: checked
Icon: ui-icon-phone
Icon Position: Icon only
Id: btnPhone
8. From the Controls > Form panel, drag a BUTTON widget and drop it
onto the design canvas, directly underneath the btnPhone button.
9. Configure the following Button properties:
Mini: checked
Icon: ui-icon-mail
Icon Position: Icon Only
Id: btnMail
10. From the Controls > Form panel, drag a BUTTON widget and drop it
onto the design canvas, directly underneath the btnMail button.
7 - 12
2013 Intel Corporation.
Using Device Features
11. Configure the following Button properties:
Mini: checked
Icon: ui-icon-navigation
Icon Position: Icon Only
Id: btnNav
12. Save the file
15. Inside the ConfigureButtons() method, bind a tap event listener to the
btnPhone button so that it launches the user's phone application and
dials their friend's phone number when tapped.
16. Verify that your code appears similar to the following:
$("#btnPhone").bind("tap", function(e) {
var ph = ContactDetail.contactData.phone;
if (ph != "") {
var telLink = "tel:" + ph;
location.href=telLink;
} else {
alert("Phone Number Not Available");
}
});
7 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
24. Launch Intel App Preview on your device, scan the QR code, and test
your app.
});
26. Inside the event handler function, insert an if-elseif-else block that
determines whether the user is using an Android device or an iOS
device. If the device is not iOS or Android, output an alert message.
} else if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
} else {
alert('Device not supported');
return;
}
});
27. Inside the if() block for Android, define a local variable named
mapsUrl and set it equal to the google maps url with GET parameters
named daddr and saddr that point to lat/lng placeholders.
if (/Android/i.test(navigator.userAgent)) {
var mapsUrl = "http://maps.google.com/maps?daddr={0},
{1}&saddr={2},{3}";
}
7 - 14
2013 Intel Corporation.
Using Device Features
28. After the code that you inserted in the prior step, replace the
placeholders with the lat/lng coordinates of the contactData and
currentPosition properties of the ContactDetail object.
mapsUrl = mapsUrl.format(
ContactDetail.contactData.lat,
ContactDetail.contactData.lng,
ContactDetail.currentPosition.lat(),
ContactDetail.currentPosition.lng()
);
29. After the code that you inserted from the prior step, launch the url in an
inAppBrowser.
window.open(mapsUrl, '_blank', 'location=yes');
30. Inside the if() block for iOS, define a local variable named mapsUrl
and set it equal to the Apple maps url with GET parameters named
daddr and saddr that point to lat/lng placeholders.
if (/Android/i.test(navigator.userAgent)) {
var mapsUrl = "http://maps.google.com/maps";
} else if (/iPhone|iPad|iPod/i.test(navigator.userAgent)){
var mapsUrl = "maps://?daddr={0},{1}&saddr={2},{3}";
} else {
/* omitted for brevity */
}
31. After the code that you inserted in the prior step, replace the
placeholders with the lat/lng coordinates of the contactData and
currentPosition properties of the ContactDetail object.
mapsUrl = mapsUrl.format(
ContactDetail.contactData.lat,
ContactDetail.contactData.lng,
ContactDetail.currentPosition.lat(),
ContactDetail.currentPosition.lng()
);
32. After the code that you inserted in the prior step, launch the url by
setting the location.href property as illustrated below:
location.href = mapsUrl;
End of Walkthrough --
7 - 15
2013 Intel Corporation.
Fast Track to Intel XDK New
} else {
You can subsequently add an event listener that is triggered whenever the
user's device changes orientation along different axes. In the following
example, the event handler simply outputs the orientation of the device to
the debugging console.
window.addEventListener('deviceorientation', function(e) {
console.log(out.format(
e.alpha,
e.beta,
e.gamma
));
});
7 - 16
2013 Intel Corporation.
Using Device Features
} else {
window.addEventListener('devicemotion', function(e) {
// acceleration info:
// e.acceleration.x
// e.acceleration.y
// e.acceleration.z
// rotation rate
// e.rotationRate.alpha
// e.rotationRate.beta
// e.rotationRate.gamma
}, false);
7 - 17
2013 Intel Corporation.
Fast Track to Intel XDK New
Steps
7 - 18
2013 Intel Corporation.
Using Device Features
Note: this feature cannot be tested on the emulator at the current time
13. Run the app and shake your phone (be careful not to drop it!). Note
that shaking the phone selects a random friend and displays his/her
detail information.
End of Walkthrough --
7 - 19
2013 Intel Corporation.
Fast Track to Intel XDK New
7 - 20
2013 Intel Corporation.
Using Device Features
7 - 21
2013 Intel Corporation.
Fast Track to Intel XDK New
In order to enable GCM for your app, you'll need to register your project in
the Google Cloud Console at http://cloud.google.com.
Rather counter-intuitively, what you need to register in the next step of the
process is not your android app, but actually a web application since it's
actually the PushMobi service that will be communicating with the GCM
to send messages and PushMobi is a web-based application.
7 - 22
2013 Intel Corporation.
Using Device Features
Once you've copied the browser key to your clipboard, you must paste it
into the Api Key (5d) field in the Intel XDK Build > Push screen as
illustrated in figure 7.
7 - 23
2013 Intel Corporation.
Fast Track to Intel XDK New
The second piece of information the project's identifier, you can get by
clicking on your project's Overview tab as illustrated by figure 11. You'll
need to copy the Project Number and paste it into the Project Id (5C) field
as illustrated in Figure 7.
Note that if your app does not require authentication, you can simply
substitute the device's unique identifer (UUID) for both the username and
password as illustrated below:
intel.xdk.notification.checkPushUser(
intel.xdk.device.uuid,
intel.xdk.device.uuid
);
7 - 24
2013 Intel Corporation.
Using Device Features
When the checkPushUser() method has completed, it will fire an event
named intel.xdk.notification.push.enable and pass in an event
object where you can inspect the result and register the user, if necessary:
var notifications = {
didAdd : false,
register: function(event) {
if(event.success === false) {
if (notifications.didAdd === false) {
notifications.didAdd = true;
intel.xdk.notification.alert(
"Doing addPushUser now...",
"My Message",
"OK"
);
intel.xdk.notification.addPushUser(
intel.xdk.device.uuid,
intel.xdk.device.uuid,
'no@email.com'
);
intel.xdk.notification.alert(
"Notifications Failed: " + event.message,
"My Message",
"OK"
);
return;
}
var msg = event.message || 'success';
intel.xdk.notification.alert(
"Notifications Enabled: " + msg,
"My Message",
"OK"
);
}
7 - 25
2013 Intel Corporation.
Fast Track to Intel XDK New
After the user's account has been registered, the receiving of push
notifications will trigger the
intel.xdk.notification.push.receive event. You can code this
handler any way that you wish, although typically you'll use the following
methods to read, parse, and delete messages:
intel.xdk.notification.getNotificationList()
Returns an array of strings that correspond to the identifiers for
received messages.
intel.xdk.notification.getNotificationData(notification id)
Returns an object containing the properties of the specified notification
Object property names include: msg and data.
intel.xdk.notification.deletePushNotifications(notification id)
Deletes the specified notification
A typical notification handler resembles the following snippet:
var notifications = {
receivedPush: function() {
var N = intel.xdk.notification;
var myNotifications=N.getNotificationList();
var len=myNotifications.length;
if(len > 0) {
for(i=0; i < len; i++) {
//Get message id
msgObj=N.getNotificationData(myNotifications[i]);
N.deletePushNotifications(msgObj.id);
return;
}
} // for
} // if()
} // function
} // class
7 - 26
2013 Intel Corporation.
Using Device Features
You can verify your event handlers and view the result of your push
notification handling by running your app in the Emulator as depicted in
Figure 12. Typing a message into the PUSHMOBI SERVICE panel
simulates the firing of an intel.xdk.notification.push.receive
event.
7 - 27
2013 Intel Corporation.
Fast Track to Intel XDK New
Testing on a Device
Test your app on a physical device by going through the application build
process, install the app on your device, and then access the PushMobi
service under the XDK Services tab as illustrated in figure 13.
7 - 28
2013 Intel Corporation.
Using Device Features
Steps
7 - 29
2013 Intel Corporation.
Fast Track to Intel XDK New
7 - 30
2013 Intel Corporation.
Using Device Features
32. Immediately after the code that you inserted in the prior step, add an
event listener that invokes the notifications.receivedpush method
when an intel.xdk.notification.push.receive event is fired.
var onDeviceReady=function(){
//hide splash screen
intel.xdk.device.hideSplashScreen();
document.addEventListener(
"intel.xdk.notification.push.enable",
notifications.register,
false
);
document.addEventListener(
"intel.xdk.notification.push.receive",
notifications.receivedPush,
false
);
};
33. Immediately after the code that you inserted in the prior step, check to
see if the device is registered with the PushMobi service. Your code
should appear as follows:
var onDeviceReady=function(){
//hide splash screen
intel.xdk.device.hideSplashScreen();
document.addEventListener(
"intel.xdk.notification.push.enable",
notifications.register,
false
);
document.addEventListener(
"intel.xdk.notification.push.receive",
notifications.receivedPush,
false
);
intel.xdk.notification.checkPushUser(
intel.xdk.device.uuid,
intel.xdk.device.uuid
);
};
End of Walkthrough --
7 - 31
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Summary
You can retrieve a device's current position by using either the Cordova
API or the build-in navigator.geolocation.getCurrentPosition() method.
You can activate the phone dialer and email client by calling special
URI's.
Support for launching the built-in navigation app varies between
platforms and delivery systems
Use the accelerometer to handle changes in orientation to the device.
The devicemotion api enables you to detect changes in how the device
is being handled including shake gestures.
Implement push notifications to enhance user engagement.
You can create your own push notification messaging front-end or
choose from a variety of third-party services.
Intel XDK New directly supports the PushMobi front-end for sending
push notifications.
You will need to configure PushMobi for each of the platforms that
you intend to support (iOS, Android, Windows Mobile)
7 - 32
2013 Intel Corporation.
Using Device Features
Unit Review
1. You must use the Cordova API to access the device's accelerometer
(true/false)?
2. Describe the process for activating the device's phone dialer and
default email application.
5. Intel XDK apps can only receive push notifications from the PushMobi
service (true/false)
7 - 33
2013 Intel Corporation.
(This page intentionally left blank)
Unit 8:
Integrating Multimedia
Unit Objectives
After completing this unit, you should be able to:
Add audio to your applications
Integrate video from different sources into your app
Use JavaScript to implement custom player controls for your media
Unit Topics
Playing Audio and Video
8-1
You can insert browser-based video into your web page using the <video>
tag. The following attributes are supported:
Attribute Description
autoplay Boolean attribute, causes the user agent to start playing
the media as soon as it is able.
controls Boolean attribute indicating whether the author has not
provided a custom controller using Javascript and would
like to use the native set of controls.
height The height of the control, in pixels
width The width of the control, in pixels
loop Boolean attribute indicating whether the media should
continue playing from the start of the file once it has
reached its end.
preload "none" indicates to the browser that that the author
will probably not need the media resource.
"metadata" hints to the browser that the author will
probably not need the media resource but that pre-
fetching the resource metadata (dimensions, first
frame, duration) is worthwhile.
"auto" hints to the browser that the author expects the
video to be played and therefore it should
optimistically cache the resource.
poster Gives the address of an image file that the user agent can
show while no video data is available. The attribute, if
present, must contain a valid non-empty URL potentially
surrounded by spaces. The image is supposed to be a
representative frame from the video.
8-2
2013 Intel Corporation.
Integrating Multimedia
Attribute Description
src The URL of the media asset. May be overridden by the
use of the <source> element.
<video
width="320"
height="240"
controls="true"
src="video1.ogg"
preload="auto"
poster="titleframe.jpg">
</video>
Support for video formats varies, with most vendors supporting either the
WebM or MP4 formats. Ironically, support for Ogg as stipulated in the
HTML5 specification, is only included in the mobile Opera and Firefox
browsers.
iOS No Yes
Blackberry No Yes
IE Mobile No Yes
</video>
8-3
2013 Intel Corporation.
Fast Track to Intel XDK New
Inserting Video with Intel XDK New
The HTML5 media element supports the following properties and methods
from which you could build a custom playback controls:
8-4
2013 Intel Corporation.
Integrating Multimedia
Read/Write Description
Property
playbackRate Returns the current playback rate
defaultPlaybackRate Returns the default playback rate, where 1.0 is
normal speed.
volume Retuns the current playback volume, in a range
of 0.0 to 1.0 where 0.0 is the quietest and 1.0 is
the loudest.
currentTime Returns the current playback position, in
seconds. Can be set to seek to a specific time.
muted Returns true if the audio is muted, false if not.
Method Description
load() Causes the element to reset and start selecting
and loading a new media resource from scratch.
pause() Sets the paused attribute to true, loads the media
resource if necessary.
play() Sets the paused attribute to false, loads the media
resource, and starts playback.
canPlayType(type) Returns the empty string (a negative response),
"maybe", or "probably" if the user agent
determines that it can play media resources of
the given type.
ondurationchange onplaying
onemptied onseeked
onerror onseeking
onloadedmetadata onstalled
onloadstart onsuspend
onpause ontimeupdate
onplay onvolumechange
onwaiting
8-5
2013 Intel Corporation.
Fast Track to Intel XDK New
Using these properties and methods, you could create your own
playback/pause button as illustrated by the following snippet:
<head>
<script language="javascript">
enablebuttons = function() {
document.getElementById('playbutton').disabled =
false;
}
playpause = function() {
var objMedia = document.getElementById('mymedia');
var objButton = document.getElementById('playbutton');
if (objMedia.paused) {
objMedia.play();
objButton.value="Pause";
} else {
objMedia.pause();
objButton.value="Play";
}
}
</script>
</head>
<body>
<video
width="320"
height="240"
controls="false"
onCanPlayThrough="enableButtons()"
id="mymedia">
</video>
<input type="button"
value="Play"
onClick="playpause()"
id="playbutton">
...
</body>
8-6
2013 Intel Corporation.
Integrating Multimedia
You can play YouTube videos from your app by inserting a video's embed
code into your app. The embed code uses an <iframe> and, as illustrated in
Figure 2, the url is located within the Share-Embed block underneath each
video.
8-7
2013 Intel Corporation.
Fast Track to Intel XDK New
Intel XDK New includes a design-time video widget that will insert the
<iframe> code for you you simply need to enter the embed URL into the
YouTube Settings panel as illustrated in figure 3.
8-8
2013 Intel Corporation.
Integrating Multimedia
The <audio> tag functions similarly to the <video> tag in that it enables
you to play a media file without requiring the use of a browser plug-in and
is typically used in mobile apps to play songs and podcasts.
Audio support in mobile browsers remains problematic for use in games.
Timing issues, lags, lack of pre-loading, inability to play multiple clips
simultaneously, and general bugginess make it unsuitable for playing short
sound-effect clips with precision timing. In the near future, the recently
introduced HTML5 Audio API may provide some relief for html5 mobile
game developers.
Supported attributes of the <audio> element include the following:
Attribute Description
autoplay Boolean attribute, causes the user agent to start playing
the media as soon as it is able.
controls Boolean attribute indicating whether the author has not
provided a custom controller using Javascript and would
like to use the native set of controls.
Note that Android devices do not have native audio
controls.
loop Boolean attribute indicating whether the media should
continue playing from the start of the file once it has
reached its end.
preload "none" indicates to the browser that that the author
will probably not need the media resource.
"metadata" hints to the browser that the author will
probably not need the media resource but that pre-
fetching the resource metadata (dimensions, first
frame, duration) is worthwhile.
"auto" hints to the browser that the author expects the
video to be played and therefore it should
optimistically cache the resource.
Note: preload is not supported on most mobile browsers.
src The URL of the media asset. Use the <source> element
to specify alternative file formats for broader user agent
compatibility.
As illustrated below, you should include both mp3 and Ogg Vorbis files in
order to support the broadest range of devices.
<audio
controls="false"
onCanPlayThrough="enableButtons()"
id="mymedia">
<source src="audiofile.mp3" type="audio/mpeg" />
<source src="audiofile.ogg" type="audio/ogg" />
</audio>
8-9
2013 Intel Corporation.
Fast Track to Intel XDK New
The <audio> element exposes a number of runtime properties that help you
determine the clip's current state:
Property Description
You can listen on the following events which are thrown by an Audio
object.
Event Description
canplay The media can be played, but may need to pause while
downloading.
ended The end of the media was reached and playback was
stopped.
8 - 10
2013 Intel Corporation.
Integrating Multimedia
The following code snippet illustrates how you could use the HTML5
Audio API to load a sound file.
var musicBuffer = null;
// Fix up prefixing
window.AudioContext = window.AudioContext ||
window.webkitAudioContext;
var context = new AudioContext();
function loadSound(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
context.decodeAudioData(
request.response,
function(buffer) {
musicBuffer = buffer;
},
function (err) {
alert("Could not decode audio file");
}
);
}
request.send();
}
loadSound('100BottlesOfBeerOntheWall.mp3');
8 - 11
2013 Intel Corporation.
Fast Track to Intel XDK New
Steps
Src: //player.vimeo.com/video/9608723
Autoplay: checked
Loop: checked
8. Click on the TEST tab.
9. Click the Push Files button
10. Test your application on a device using Intel App Preview. You should
be able to play the Vimeo video by tapping on the Drink! tab of the
app.
8 - 12
2013 Intel Corporation.
Integrating Multimedia
15. Enter the following Video Settings:
End of Walkthrough --
8 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Summary
You can play audio and video without the user of a plug-in
The HTML5 <audio> and <video> elements have API methods that
you can use to design custom player controls.
You should support both WebM and MP4 video formats to ensure the
highest degree of compatibility.
Intel XDK New has design-time widgets for HTML5 video as well as
playing assets hosted on YouTube.com and Vimeo.com
The <audio> element is not well-suited for playing sound effects in
games.
The HTML5 Audio API contains a very robust set of methods for
handling audio, however, it is not currently supported by the native
Android browser.
8 - 14
2013 Intel Corporation.
Integrating Multimedia
Unit Review
1. What is the purpose of the <video> element's poster property?
2. What video file formats are natively supported by iOS and Android?
8 - 15
2013 Intel Corporation.
(This page intentionally left blank)
Unit 9:
Theming
Unit Objectives
After completing this unit, you should be able to:
Understand how to work with vendor prefixes
Add web fonts to your application
Enhance your app's typography
Apply background gradients and images
Use ThemeRoller to visually prototype a application widgets
Unit Topics
Working with CSS3 on Mobile Devices
Enhancing Fonts and Typography
Enhancing Backgrounds
Working with ThemeRoller
9-1
Prefix Description
-ms- Mobile IE
Consequently, most app developers typically use a 3rd party tool to handle
vendor prefixes and make CSS authoring a bit less redundant. Two of those
products are Sass and LESS.
9-2
2013 Intel Corporation.
Theming
About Sass
Sass is essentially a stylesheet compiler. You author .scss files (Sassy CSS)
which are then converted into production-ready CSS files by a command-
line utility.
Vendor prefixes in Sass are handled through a mechanism called mixins
which are analogous to javascript functions. However, whereas a
JavaScript function typically returns result data based on a set of
parameters, a Sass mixin generates css styles based on passed-in data.
For instance, the following declaration in Sass:
.myCustomClass {
@include border-radius(5px);
}
9-3
2013 Intel Corporation.
Fast Track to Intel XDK New
About LESS
9-4
2013 Intel Corporation.
Theming
Downloading a Font
CSS3 capable browsers can download fonts and use them to format your
text. Use the @font-face selector to define a font name and associated
download url. You can then reference the font in subsequent style
definitions as indicated below:
@font-face {
font-family: 'Droid Sans';
src: url(fonts/Droid_Sans.ttf);
}
h1{
font-family: 'Droid Sans';
}
Property Description
<style>
h1 {
text-fill-color: green;
text-stroke-color: orange;
text-stroke-width: 2px;
font-family: arial;
font-size: 40px;
}
</style>
<h1>This is a test</h1>
9-5
2013 Intel Corporation.
Fast Track to Intel XDK New
The CSS3 text-shadow property enables you to cast a shadow behind your
text as indicated below:
<style>
p {
font-family:arial;
font-size: 30px;
text-shadow:2px 2px 5px #000;
}
</style>
<p>This is a demonstration of text shadows</p>
9-6
2013 Intel Corporation.
Theming
Applying Transparency
#appetizer {
background:url(../images/appetizer.jpg);
width: 475px;
height: 102px
}
</style>
9-7
2013 Intel Corporation.
Fast Track to Intel XDK New
<div id="test">
Lorum Ipsum and more pseudo-latin ridiculousness
</div>
<style>
#myarticle{
column-count: 2;
column-gap: 10px;
/* Column-count not implemented yet */
-moz-column-count: 2;
-webkit-column-count: 2;
/* Column-gap not implemented yet */
-moz-column-gap: 22px;
-webkit-column-gap: 22px;
}
</style>
<div id="myarticle">
<p>Lorem Ipsum...and more latin nonsense</p>
</div>
9-8
2013 Intel Corporation.
Theming
As illustrated in Figure 7, Google Fonts has a filter panel in its left column
that enables you to search for fonts based on font type (serif, sans-serif,
display, and handwriting) as well as thickness, slant, and width.
Studies have shown that, on mobile devices, sans-serif and display fonts
are more readable than serif fonts.
After you select a font, the Google Fonts interface generates the <link>
element and font-family css declarations that you'll use to invoke the font
from within your app. It also displays an estimate impact on page load
time.
9-9
2013 Intel Corporation.
Fast Track to Intel XDK New
Adobe Edge Web Fonts gives you access to a vast web font library made
possible by contributions from Adobe, Google, and designers around the
world. The fonts are served by Typekit which is a subscription-based
library of hosted, high-quality fonts that was acquired by Adobe in 2011.
9 - 10
2013 Intel Corporation.
Theming
Steps
9 - 11
2013 Intel Corporation.
Fast Track to Intel XDK New
12. In the <style> block near the top of the file, add a body and paragraph
tag selector that specifies Rambla as the font-family and bold as the
font-weight.
body, p {
font-family: 'Rambla', sans-serif;
font-weight: bold;
}
End of Walkthrough --
9 - 12
2013 Intel Corporation.
Theming
Enhancing Backgrounds
You can enhance the backgrounds of images in CSS3 by specifiying
background gradients and background images for html elements. If you
plan to use background images, consider base-64 encoding them into your
spreadsheet for improved performance.
<style>
body {
background-image: -webkit-gradient(
linear, left top, left bottom,
color-stop(0%,#ffffff),
color-stop(50%,#f20e0e),
color-stop(100%,#3e21ff)
);
// other vendor prefixes omitted for brevity
}
</style>
9 - 13
2013 Intel Corporation.
Fast Track to Intel XDK New
Most designers choose to create gradients visually, and many use the
Ultimate CSS Gradient generator depicted in Figure 10.
9 - 14
2013 Intel Corporation.
Theming
body
{
background:url(beercan.gif);
background-size: cover;
background-repeat:no-repeat;
}
Specifying background-position
Value Description
9 - 15
2013 Intel Corporation.
Fast Track to Intel XDK New
Base-64 encoding enables you to take a binary image file and encode it as a
text string that can be included as part of a stylesheet. Encoding images
directly into a stylesheet gives you better startup performance since it
eliminates the need for the browser to make separate http requests for each
image. A drawback, however, is that the process usually increases the
image's data size by approximately 30%.
Websites like www.base64-image.de provide free services for converting
images to base-64.
Images encoded into a stylesheet typically appear as follows (note that the
image data has been truncated for brevity):
.body {
background-image: url('data:image/png;base64,iVBORw==');
background-size: cover;
background-repeat: no-repeat;
}
9 - 16
2013 Intel Corporation.
Theming
CSS3 enables you to specify multiple background images that are stacked
on top of each other as transparency layers.
The following examples illustrate the effect of combining a background
images with a radial gradient to produce a glossy-wood effect:
.ui-header-fixed {
background-image: url('resources/headerbackground.png')
}
.ui-header-fixed {
background-image: -webkit-linear-gradient(#9f5628,#5d2f17);
}
.ui-header-fixed {
background-image: url('resources/headerbackground.png'),
-webkit-linear-gradient(#9f5628, #5d2f17) !important;
}
9 - 17
2013 Intel Corporation.
Fast Track to Intel XDK New
Steps
background-image: url('../resources/background.png');
background-size: cover;
11. Save the file and test in the emulator. You should see that there's now
beer in the background in each page of your app.
9 - 18
2013 Intel Corporation.
Theming
Base-64 Encode an Image
12. Open a web browser to the following url:
www.base64-image.de
22. Add another class selector to the definition that you inserted in the
prior step named .ui-footer-fixed. Your code should appear as follows:
.ui-header-fixed, .ui-footer-fixed {
background-image: url('../resources/headerbackground.png'),
-webkit-linear-gradient( #9f5628, #5d2f17) !important;
23. Save the file and test in the emulator. Your header and footer should
now have a glossy-wood background.
26. Save the file and test. Note that the selected button style class remains
inconsistent with the rest of the footer.
9 - 19
2013 Intel Corporation.
Fast Track to Intel XDK New
27. Return to the custom.css file.
28. At the top of the file insert the following definition to make the
selected button style consistent with the rest of the control bar:
.ui-btn.ui-btn-b {
background: transparent !important;
border-color: transparent !important;
color: #DAA520 !important;
text-shadow: 0px 1px rgba(100, 100, 100, 0.3) !
important;
}
29. Save the file and test. Your output should appear similar to figure 9.
Note that the list views in the Friends and Beers list still need to be
themed.
End of Walkthrough --
9 - 20
2013 Intel Corporation.
Theming
The ThemeRoller interface has 3 major zones: the left column contains the
inspector panel, along the top is the QuickSwatch/Kuler bar, and below this
is the preview window.
Use the Inspector panel to set global theme settings on the first tab and
tweak the individual style options for each swatch.
When you drag and drop a color from the QuickSwatch panel onto an
element in the preview panel, ThemeRoller automatically calculates
text color and shadow, borders, gradients and button states. The sliders
make it easy to adjust the lightness and saturation of the colors. Use
the Adobe Kuler Swatches to load complementary color palettes from
Adobe's popular color palette sharing site.
The Preview panel shows a sample of common jQuery Mobile
widgets that live update each time you make a change to the theme so
you can quickly test and tweak the theme.
9 - 21
2013 Intel Corporation.
Fast Track to Intel XDK New
Steps
9 - 22
2013 Intel Corporation.
Theming
17. Return to Intel XDK New
18. Open index.html in Code mode.
19. Immediately preceeding the <link> tag to custom.css, insert a <link>
tag that points to the css/fwb.css file.
20. Test your app in the emulator. Note that the list of beers and friends are
now themed.
End of Walkthrough --
9 - 23
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Summary
Some CSS3 style properties require vendor prefixes.
There are a number of 3rd party tools that you can use to help mitigate
vendor-prefix compatibility issues.
CSS3 supports downloadable web fonts.
Google and Adobe offer a combined 1000+ fonts freely available for
download.
You can combine text-shadow and transparancy effects to output an
inset-text effect.
CSS3 enables you to combine background images and gradients to
produce exciting effects.
Base-64 encode your application's images in order to reduce the
number of http requests that must be made and improve app
performance.
You can theme your app by overriding jQuery Mobile CSS classes and
by generating a CSS file from ThemeRoller.
9 - 24
2013 Intel Corporation.
Theming
Unit Review
1. What are the benefits and drawbacks to using base-64 encoding?
2. List three tools that you can use to either visually prototype CSS3
styles or mitigate vendor prefix issues.
4. Which style class can you override to set a background image for all of
the pages in your app?
9 - 25
2013 Intel Corporation.
(This page intentionally left blank)
Unit 10:
Going into Production
Unit Objectives
After completing this unit, you should be able to:
Unit Topics
Creating a Production Build for Android
10 - 1
For Android builds, the overview tab will indicate that your app is ready to
be packaged into a production-ready .apk file. However, while this is
technically a true statement, there are a number of settings that you will
want to modify before you proceed with packaging.
The Details panel allows you to set your application title, version,
permissions, orientation, and codebase.
The Assets panel enables you to configure your application's startup
orientation as well as launch icon and startup screens.
The Plugins panel gives you the ability to upload Cordova plugins for
use in your app.
The Credentials tab lets you enter credentials for working with the
Facebook APIs.
The Push tab configures your app for Push Notification support from
the Google Cloud Messaging Service and PushMobi.
10 - 2
2013 Intel Corporation.
Going into Production
10 - 3
2013 Intel Corporation.
Fast Track to Intel XDK New
10 - 4
2013 Intel Corporation.
Going into Production
You can lock rotation using the intel.xdk bridge library by invoking the
following methods:
Use the intel.xdk.device.setRotateOrientation(str) method to the
preferred orientation (landscape or portrait)
Use the intel.xdk.device.setAutoRotate(bool) method to lock the
orientation.
The following code snippet locks an application into a portrait orientation:
<script type="text/javascript">
intel.xdk.device.setRotateOrientation("portrait");
intel.xdk.device.setAutoRotate(false);
</script>
The plugins tab, as illustrated in Figure 4, enables you to create and upload
cordova API extensions.
http://intel.ly/1dpj1B0
10 - 5
2013 Intel Corporation.
Fast Track to Intel XDK New
As depicted in Figure 5, the App Credentials panel is where you must enter
additional credentials if your app makes use of the Intel XDK native
application Facebook integration.
10 - 6
2013 Intel Corporation.
Going into Production
As described in unit 7, you will need to add information into the Push
notifications panel, in order to receive push notifications from Intel's
PushMobi service.
10 - 7
2013 Intel Corporation.
Fast Track to Intel XDK New
Steps
10 - 8
2013 Intel Corporation.
Going into Production
Create a Build
16. Click on the Overview tab.
17. Click the Build App Now button.
18. Click the Download Build button and save the file to your computer.
End of Walkthrough
10 - 9
2013 Intel Corporation.
Fast Track to Intel XDK New
Unit Summary
Accessing some hardware functions require that you grant permissions
to your app.
Application icons and startup images are automatically resized during
the build process in order to support multiple device resolutions.
Use the intel.xdk.device methods to lock the application into using a
specific orientation.
Facebook and Push notification support require that you enter
additional credentials during the build process.
You can email .apk files to your users or post them to a web server.
App distribution does not require uploading your app to Google Play.
Always test your app on a physical device prior to uploading it to an
app store.
10 - 10
2013 Intel Corporation.
Going into Production
Unit Review
1. Which device resource permissions can be set within the Build
process?
10 - 11
2013 Intel Corporation.