intro to appcelerator

Post on 09-May-2015

953 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Prepared byMohab Tarek@MohabTarek

Native Development

Java Objective-C

• 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

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)

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

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

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

To start development…

Titanium Studio

• Eclipse-- (was Aptana Studio)

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

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

Ti Studio (why it so powerful)…

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

Ti Studio (why it so powerful)…

• Syntax highlighting

Ti Studio (why it so powerful)…

• Content assist and more…

Ti Studio (why it so powerful)…

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

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

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

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>

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

Project structure…

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 ???

Let’s Get into the interesting part. Coding…

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();

Create Window

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

Create Label

Create Button

Create button with add event listener

Add sub view to Window or View

Log methods

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.

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.

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.

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; }

Animate with UI elementsBefore start

After complete

Connect to Web Services

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

Connect to Web Services

• How to send data using post method?

• How to stop request

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

Keep your app fresh. Use web services

• 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

Database code snippets

• Running SQL Queries against the DB

• We can also get number of Rows affected

• What about SELECT Query?

Database code snippets

Database example

• 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

• strings.xml

Our App in different languages

http://bit.ly/TiLang

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') }

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

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

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.)

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

Useful Ti Modules

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

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

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

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

Some Tools of the Trade

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

Ti.Platform.osname

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

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

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

Platform Resources

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

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

Dealing with multiple resolutions and densities

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.

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)

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

Many Screen Types

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

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”

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

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

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

Structuring your Titanium application for cross-

platform

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

Rich client applications (like Ti Mobile apps) should strive

to be:

event-driven and

component-oriented

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

Interaction Events• Interaction events you

know:o clicko swipeo changeo focuso blur

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)

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

Being component-oriented helps us build cross-platform

more easily.

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

• 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

File system

File System code snippets

Map view code snippets (cont)…

Few more code snippets (cont)…

iOS

Android

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

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();

}

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);

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

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

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:

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!

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)

Future Platform Support

• Blackberry• WinPhone7

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

top related