83
Prepared by Mohab Tarek @MohabTarek

Intro to appcelerator

Embed Size (px)

Citation preview

Page 1: Intro to appcelerator

Prepared byMohab Tarek@MohabTarek

Page 2: Intro to appcelerator

Native Development

Java Objective-C

Page 3: Intro to appcelerator

• Titanium is a JavaScript runtime that gives you native access to the platform’s controls

• You are not building a app via html/css/js (i.e. PhoneGap)

Appcelerator Titanium Mobile

JavaScript

Page 4: Intro to appcelerator

How Titanium Mobile Works

• You write code in JavaScript

• At runtime, your application has 3 major components:o JavaScript source code (minified and inlined, but not compiled, into Java/Obj-C strings)o Titanium API implementation in the native OSo JavaScript interpreter (V8/Rhino for Android, JavaScriptCore for iOS)

• The JavaScript interpreter runs your JavaScript code in an environment with proxies for the native objects (windows, controls, etc)

Page 5: Intro to appcelerator

Our Application

UI API Phone API

Bridge - JavaScript -Java / JavaScript - Objective C

OS - Android / iPhone

Native Android App Native iOS App

Optional Modules

Titanium MobileApplication Source Files

Page 6: Intro to appcelerator

JS files to native objective code

• JS is statically analyzed• Ti’s Python build scripts interact with native SDK tools .• Native project stub will created• JS precompiled to bytecode(Android) or inlined in a generated

C file(iOS)• Your JS and native code package together with V8/Rhino or

JavaScriptCore to interpret JS code at runtime

Page 7: Intro to appcelerator

• PC or Mac machine (for iOS development)• XCode with iOS SDK• JDK 6 x86• Android SDK• Titanium Studio with SDK

To start development…

Page 8: Intro to appcelerator

Titanium Studio

• Eclipse-- (was Aptana Studio)

• Editor• Formatting• Code-completion• Build• Debug• Release

Page 9: Intro to appcelerator

• It always notifies you about latest SDK and Studio updates .

Ti Studio (why it so powerful)…

Page 10: Intro to appcelerator

• It is so smart, because it catches mistakes immediately!

Ti Studio (why it so powerful)…

Page 11: Intro to appcelerator

• Syntax highlighting

Ti Studio (why it so powerful)…

Page 12: Intro to appcelerator

• Content assist and more…

Ti Studio (why it so powerful)…

Page 13: Intro to appcelerator

Anatomy of a project

Project directory build/

android/iphone/

Resources/app.js

manifesttiapp.xml Project files

Resource files: JS code, images, sounds, Sqlite DBs, etc.

Build folders, per platform

Page 14: Intro to appcelerator

App File Structure

• I18n\ - Internationalization files• modules\ - Third-Party (or Appcelerator) native modules• Resources\

o app.js – Startup fileo images\ - Generic Imageso android\ - Android-specific images

• images\high / etc – Android density/screen-size dirso iphone\ - iOS-specific images

• @2x fileso lib\, ui\, whatever\ - your source file dirs

Page 15: Intro to appcelerator

manifest

#appname: whymca#publisher: olivier#url: http://www.whymca.org#image: appicon.png#appid: com.whymca.test#desc: undefined#type: mobile#guid: 746e9cb4-49f6-4afe-af0b-5de9f0116f65

Page 16: Intro to appcelerator

tiapp.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<ti:app xmlns:ti="http://ti.appcelerator.org"> <deployment-targets> <target device="iphone">true</target> <target device="ipad">false</target> <target device="android">true</target> </deployment-targets> <id>com.whymca.test</id> <name>whymca</name> <version>1.0</version> <publisher>olivier</publisher> <url>http://www.whymca.org</url> <description>not specified</description> <copyright>2011 by olivier</copyright> <icon>appicon.png</icon> <persistent-wifi>false</persistent-wifi> <prerendered-icon>false</prerendered-icon> <statusbar-style>default</statusbar-style> <statusbar-hidden>false</statusbar-hidden> <fullscreen>false</fullscreen> <navbar-hidden>false</navbar-hidden> <analytics>false</analytics>

<guid>746e9cb4-49f6-4afe-af0b-5de9f0116f65</guid>

<iphone><orientations device="iphone"><orientation>Ti.UI.PORTRAIT</orientation></orientations><orientations device="ipad"><orientation>Ti.UI.PORTRAIT</orientation><orientation>Ti.UI.UPSIDE_PORTRAIT</orientation><orientation>Ti.UI.LANDSCAPE_LEFT</orientation><orientation>Ti.UI.LANDSCAPE_RIGHT</orientation></orientations></iphone><android

xmlns:android="http://schemas.android.com/apk/res/android">

</android><modules></modules></ti:app>

Page 17: Intro to appcelerator

app.js• Starting point of App• In app.js, we generally take care of a few things:

o Bootstrap the application with any data we needo Check for dependencies like device type, platform version or network

connectiono Require and open our top-level UI componento Background service for both iOS and Android

Page 18: Intro to appcelerator

Project structure…

Page 19: Intro to appcelerator

Getting Titanium Mobile

Step 1: Sign up for Appcelerator• https://my.appcelerator.com/auth/signup• “App EXPLORE” plan = Free: Build, test, ship, sell for free• Additional plans available (more analytics, cloud, support):

http://www.appcelerator.com/plans-pricing

Step 2: Download Titanium Studio• http://www.appcelerator.com/platform/titanium-studio

Step 3:• Profit ???

Page 20: Intro to appcelerator

Let’s Get into the interesting part. Coding…

Page 21: Intro to appcelerator

Hello Worldvar win = Ti.UI.createWindow({ title: 'Hello, World!', layout: 'vertical', backgroundColor: 'white'});

var helloLabel = Ti.UI.createLabel({ text: 'Hello World', color: 'black', font: { fontSize: '20sp' }, height: '40dp', width: '250dp'});win.add(helloLabel);

var helloButton = Ti.UI.createButton({ title: 'Click me!', font: { fontSize: '20sp' }, top: '20dp', height: '40dp', width: '250dp'});

helloButton.addEventListener('click', function() { alert('you clicked me!');});win.add(helloButton);

win.open();

Page 22: Intro to appcelerator

Create Window

We can also set properties like thiswin.backgroundColor="#F00";win.setBackgroundColor("#F00");

Page 23: Intro to appcelerator

Create Label

Page 24: Intro to appcelerator

Create Button

Page 25: Intro to appcelerator

Create button with add event listener

Page 26: Intro to appcelerator

Add sub view to Window or View

Page 27: Intro to appcelerator

Log methods

Page 28: Intro to appcelerator

Layout (composite )

• composite (or absolute). Default layout. A child view is positioned based on its positioning properties or "pins" (top, bottom, left, right and center). If no positioning properties are specified, the child is centered.

• The child is always sized based on its width and height properties, if these are specified. If the child's height or width is not specified explicitly, it may be calculated implicitly from the positioning properties. For example, if both left and center.x are specified, they can be used to calculate the width of the child control.

Page 29: Intro to appcelerator

Layout (vertical)

• Children are laid out vertically from top to bottom. The first child is laid out top units from its parent's bounding box. Each subsequent child is laid out below the previous child. The space between children is equal to the upper child's bottom value plus the lower child's top value.

• Each child is positioned horizontally as in the composite layout mode.

Page 30: Intro to appcelerator

Layout (vertical)

• Horizontal layouts have different behavior depending on whether wrapping is enabled. Wrapping is enabled by default (the horizontalWrap property is true).

• With wrapping behavior, the children are laid out horizontally from left to right, in rows. If a child requires more horizontal space than exists in the current row, it is wrapped to a new row. The height of each row is equal to the maximum height of the children in that row.

Page 31: Intro to appcelerator

Include Vs. Require

• Ti.include(‘filename.js');o is to be used when you want to include some other js file within another file.o copy-pastes source code every time it's called.o Used when wanting to define global methods or variables [defined once in top of file.js].

• Require(filename.js).methodo parses module's source code just once and it returns same object that is exported every time it is

called.o Used when calling a method or variable from another file o fontSize : require('src/Settings1').getFontNormal()o var _isAndroidTablet = require('src/GlobalVariables').isAndroidTablet();

o Another File code exports.isAndroidTablet = function() {

if(scWidth>scHeight && osname=='android')return true;return false; }

Page 32: Intro to appcelerator

Animate with UI elementsBefore start

After complete

Page 33: Intro to appcelerator

Connect to Web Services

open( “GET|POST”, “[HTTP://URL…]”, “[TRUE|FLASE – async call]”] )This async parameter only for iOS

Page 34: Intro to appcelerator

Connect to Web Services

• How to send data using post method?

• How to stop request

Page 35: Intro to appcelerator

Request.open(“SHOW”,”DEMO”)

Keep your app fresh. Use web services

Page 36: Intro to appcelerator

• Install will copy SQLite database file to device's internal storage. If file is there, it just uses the open method

• We can use Ti.App.Properties to set db install to true. For E.g. Ti.App.Properties. setBool(‘isDbInstalled’,true)

• Open will automatically open the DB to perform CRUD operations

Database

Page 37: Intro to appcelerator

Database code snippets

• Running SQL Queries against the DB

• We can also get number of Rows affected

Page 38: Intro to appcelerator

• What about SELECT Query?

Database code snippets

Page 39: Intro to appcelerator

Database example

Page 40: Intro to appcelerator

• Create 2 letter folder inside “i18n” (18 stands for the number of letters between the first i and last n in internationalization) in root folder.

• Create Locale folder in it• In that Locale folder just keep strings.xml

Internationalization

http://bit.ly/TiLang

Page 41: Intro to appcelerator

• strings.xml

Our App in different languages

http://bit.ly/TiLang

Page 42: Intro to appcelerator

Internationalization example

<resources><string name="en_NoOfBills">No of bills</string><string name="ar_NoOfBills"> الفواتير <string/>عدد

</resources>

var lang = require('src/Settings1').getLang();var lblTitle = Ti.UI.createLabel({text:L(lang+’ NoOfBills') }

Page 43: Intro to appcelerator

Ti JavaScript API• UI

– Titanium.UI – Titanium.UI.Android – Titanium.UI.Clipboard – Titanium.UI.iOS – Titanium.UI.iPad – Titanium.UI.iPhone– Titanium.Map

• Sensors– Titanium.Accelerometer– Titanium.Geolocation– Titanium.Gesture

• Networking– Titanium.Network– Titanium.XML– Titanium.Facebook– Titanium.Yahoo– Titanium.Analytics

• Device integration– Titanium.Platform– Titanium.Contacts

– Titanium.Media – Titanium.Android – Titanium.Android.Calendar – Titanium.Android.NotificationManager– Titanium.App.iOS – Titanium.App.Android

• Data Persistence– Titanium.Database – Titanium.Filesystem– Titanium.App.Properties

• i18n– Titanium.Locale

• Utilities/helpers– Titanium – Titanium.App – Titanium.API – Titanium.Utils

http://developer.appcelerator.com/apidoc/mobile

Page 44: Intro to appcelerator

Extending the API: why?

• Accessing specific OS features• Leveraging existing native libraries• Optimizing critical portions of the app• Extending/ameliorating portions of the Titanium Mobile

framework

Page 45: Intro to appcelerator

Extending the API: how?

• Creating a fork of Titanium Mobile’s source code on githubo Unflexible approach

• You put your hands in the heart of the framework• Maintaining a separate branch can be tedious and

costlyo There are situations where this is the cheaper

approach• E.g. when needing to extend the functionality of core

modules of the framework (networking, maps, ecc.)

Page 46: Intro to appcelerator

Extending the API: how?

• Creating one or more native modules throught the Titanium Module SDKo Great flexibilityo Easy to distribute as

• Open Source• Binary packages• Appcelerator Ti+Plus Marketplace (?)

• Add files to modules folder to specific

Android or iOS

Page 47: Intro to appcelerator

Useful Ti Modules

Page 48: Intro to appcelerator

Moduli nativi – some examples

• Android barcode scanner (Zxing wrapper)o https://github.com/mwaylabs/titanium-barcode

• iOS ZipFile (create/decompress zip files)o https://github.com/TermiT/ZipFile

• iOS TiStoreKit (in app purchase)o https://github.com/masuidrive/TiStoreKit

• iOS TiSMSDialog (in app sms sending)o https://github.com/omorandi/TiSMSDialog

• Appcelerator Titanium modules (sample modules)o https://github.com/appcelerator/titanium_modules

Page 49: Intro to appcelerator

KitchenSink• https://github.com/appcelerator/KitchenSink/

Page 50: Intro to appcelerator

50http://www.appcelerator.com | @appcelerator

Cross-platform Strategy• If possible, build and test your application for multiple

platforms from the start• Understand the cost of using platform-specific native UI

elements• Separate business logic and UI construction• Smaller UI components are easier to maintain across

platforms than large ones• Test on many devices and resolutions

Page 51: Intro to appcelerator

51http://www.appcelerator.com | @appcelerator

Some Tools of the Trade

Page 52: Intro to appcelerator

52http://www.appcelerator.com | @appcelerator

Ti.Platform.osname

A little extra sugar for branching based on OS...

Page 53: Intro to appcelerator

53http://www.appcelerator.com | @appcelerator

Usage...

use as a convenient way to branch logicbased on operating system, or...

...a convenient way to choose a value based on operating system

Page 54: Intro to appcelerator

54http://www.appcelerator.com | @appcelerator

Platform Resources

Code files, images, or any other resource can be swapped out on a per-platform basis

Page 55: Intro to appcelerator

55http://www.appcelerator.com | @appcelerator

Dealing with multiple resolutions and densities

Page 56: Intro to appcelerator

56http://www.appcelerator.com | @appcelerator

Terms and Concepts

• Resolution: The total number of physical pixels on a screen• Density: the spread of pixels across an inch of the actual

screen (DPI)

When defining Android user interfaces, the top/bottom/left/right/height/width/font etc. values you use are based on RESOLUTION. SCREEN DENSITY can be used to determine density-appropriate visual

assets to use.

Page 57: Intro to appcelerator

57http://www.appcelerator.com | @appcelerator

Example

Same Physical Size

Resolution: 320x480 Resolution: 480x800

Medium Density (160dpi)High Density (240dpi)

Smaller Physical Size

Resolution: 240x320

Low Density (120dpi)

Page 58: Intro to appcelerator

58http://www.appcelerator.com | @appcelerator

Many Screen Types

http://developer.android.com/guide/practices/screens_support.html

Page 59: Intro to appcelerator

59http://www.appcelerator.com | @appcelerator

Contrast with iOS

• iPhone layout is always based on a 320x480 point system, regardless of screen density/pixels

• Retina display devices (high density display) require high-res images (@2x)

320 “points”

480 “points”

Page 60: Intro to appcelerator

60http://www.appcelerator.com | @appcelerator

Multiple Resolutions

• Ti.Platform.displayCapso platformWidtho platformHeight

• Based on available screen real estate, you may change the size or layout of your UI

• Use the available emulator skins and devices to test layouts on multiple resolutions

• Use top/bottom/left/right for sizing where possible

Page 61: Intro to appcelerator

61http://www.appcelerator.com | @appcelerator

Multiple Densities

• Even if the available screen resolution is the same, higher density screens call for higher resolution assets

• Provide density-specific images in the ‘android/images’ resource directory

• Provide highest resolution images, it will scale to rest of images , you can modify by adding other images

Page 62: Intro to appcelerator

62http://www.appcelerator.com | @appcelerator

Structuring your Titanium application for cross-

platform

Page 63: Intro to appcelerator

63http://www.appcelerator.com | @appcelerator

Rich client applications (like Ti Mobile apps) should strive

to be:

event-driven and

component-oriented

Page 64: Intro to appcelerator

64http://www.appcelerator.com | @appcelerator

Interaction Events• Interaction events you

know:o clicko swipeo changeo focuso blur

Page 65: Intro to appcelerator

65http://www.appcelerator.com | @appcelerator

Custom Events• Custom events you might not use (but should!)• Custom events can be app wide• Custom events can be specific to your app’s components

(business events)

Page 66: Intro to appcelerator

66http://www.appcelerator.com | @appcelerator

Being component-oriented helps us build cross-platform

more easily.

Page 67: Intro to appcelerator

67http://www.appcelerator.com | @appcelerator

Component-Oriented• Your application is composed of a library of application-

specific components you create• The smaller the component, the easier it is to make each

components work across platforms• Encourages the encapsulation and reuse of UI components

Page 68: Intro to appcelerator

• Ti for Titanium• L for Titanium.Locale.getString• alert for Titanium.UI.createAlertDialog• And also remember about Code snippets

o For e.g. :- button then {ctrl + space} and see the magic..

Macro

Page 69: Intro to appcelerator

File system

File System code snippets

Page 70: Intro to appcelerator

Map view code snippets (cont)…

Page 71: Intro to appcelerator

Few more code snippets (cont)…

iOS

Android

Page 72: Intro to appcelerator

Android Manifest

• Android Manifest can be overridden• Add custom behavior or capabilities to you app• Copy the one generated by Titanium • Modify generated file and then put it inThe following folder

Page 73: Intro to appcelerator

Tips & Tricks• Android has a problem in GC so when closing a page it doesn’t

release it’s objects Ex. Used in changing languages.

if(require('src/Settings1').getLang() != lang){if (win1.children) {for (var c = win1.children.length - 1; c >= 0; c--) {win1.remove(win1.children[c]);win1.children[c] = null;}}lang = require('src/Settings1').getLang();Draw();

}

Page 74: Intro to appcelerator

Tips & Tricks..• There is only one map view can be added to view in app• If a view has MapView and another one have map app will

crash immediately .• When adding annotations remove previously added

annotation first and event listeners

mapview.removeAllAnnotations();mapview.removeEventListener('click', annotationListener);

Page 75: Intro to appcelerator

Packaging ..• In order to build applications made for the Android Marketplace, you

need to create a distribution key on your local computer. This key is used to digitally sign your app.

• Open the Terminal or Prompt type the following o cd /<path to your android sdk>/tools

• we need to use the Java keytool located in this directory$ keytool -genkey -v -keystore com.othaim.iktissab -alias Iktissab –keyalg RSA -validity 10000

• Press Enter and execute the command and you'll be asked a series of questions. You need to provide a password for the keystore - it would be wise to write it down as you will need it to package your app later.

• Now your key will be exported and saved to the directory you were currently in.

• Now your key will be exported and saved to the directory you were currently in. In our case, this is the tools directory under our Android SDK folder

Page 76: Intro to appcelerator

Packaging ..

• Open your project in Titanium Studio. Make sure your project is selected in the Project explorer page, and then select the Distribution button followed by the Distribute – Android option, as seen in the following screenshot

Page 77: Intro to appcelerator

Packaging ..

• You will need to enter in the distribution location (where you want the packaged APK file saved to) and the location of the keystore file you created in the previous recipe, along with the password and alias you provided earlier. After you enter in that information it should look something like the following screenshot:

Page 78: Intro to appcelerator

Pros

• One codebase for two platformso You’ll (theoretically) spend less time than writing two native appso Maintenance on one codebase should be easier in the long run

• Native interface controlso Your apps can look just like native ones

• Might be able to reuse your JavaScript in other parts of your projecto eg., Web front-end, Node.js backend

• Platform is open-sourceo https://github.com/appcelerator/titanium_mobile

• JavaScript is fun!

Page 79: Intro to appcelerator

Cons

• Platform is young and still changing

• Need to learn a new platform / SDK / quirkso Knowing the ins & outs of native iOS / Android will help

• You’ll still have lots of if(iOS){} and if(android){}o LEGO Minifig Collector has 24 blocks of code that are Android or iOS specific

• Performance isn’t 100% of a native app

• SDK/API Documentation is weak (but getting better)

• Q&A support forum is a mess (use SO instead)

Page 80: Intro to appcelerator

Future Platform Support

• Blackberry• WinPhone7

Page 83: Intro to appcelerator

Credits• Appcelerator Titanium by Nic Jansma @NicJ• Extending Titanium Mobile through Native Modules by Olivier Morandi• Native Android Applications with Titanium by Marshall

Culpepper (@marshall_law) and Kevin Whinnery (@kevinwhinnery)• Getting started with Titanium by Next-Generation Mobile Platform• Appcelerator Titanium Smartphone App Development Cookbook book