Your SlideShare is downloading. ×

Titanium appcelerator sdk

1,241

Published on

an introduction to the titanium mobile sdk …

an introduction to the titanium mobile sdk
(cross platform programming seminar at university of pisa, july 2012)

Published in: Technology, News & Politics
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,241
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
69
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Transcript

    • 1. Titanium SDK Alessio Ricco @alessioricco 1
    • 2. KitchenSink• Titanium Mobile sample project• Demonstrates the APIs available• Great for API samples• Obsolete application structure 2
    • 3. KitchenSink is Cross Platform 3
    • 4. Titanium.UI• View• Controls• Windows 4
    • 5. Titanium.UI:ViewsViews are containers that host visual elements such as controlsor other views.Views can have their properties customized, such as their bordercolor and radius, can fire events such as swipe events or touches,and can optionally contain a hierarchy or other views as children.In Titanium, most views are specialized to perform both a visualfunction and set of interaction behaviors such as Table View orCoverflow View.Views are always named with the suffix View. 5
    • 6. Titanium.UI: ControlsControls, or sometimes referred as widgets, are visual elementssuch as sliders, buttonsand switches.They provide a visual element which has a defined behavior andtypical have special configuration and special events.Controls themselves are views and also inherit a viewsproperties, functions and events. 6
    • 7. Titanium.UI: WindowsWindows are typically top-level visual constructs that are themain part of your interface.An application will always have at least one window and windowscan take different shapes and sizes, can have display andinteraction properties such as fullscreen or modal and can becustomized, such as changing their opacity or background color.Windows themselves are views and also inherit a viewsproperties, functions and events.There are a few specialization of Windows such as a Tab Groupwhich offer additional behavior beyond the basic Window. 7
    • 8. Factory pattern Titanium uses the Factory Pattern for constructing objects and a general naming pattern for APIs. For example, to construct a Alert Dialog, you call the method createAlertDialog. To create a TextArea, you call the method createTextArea. Once an object is created, it will be available until it goes out of scope. 8
    • 9. Event HandlerstabGroup.addEventListener(blur, function(e){ Event listeners must be defined before! Titanium.API.info(tab blur - new index +e.index + old index + e.previousIndex); their respective events are likely to be}); fired, otherwise they are not guaranteed to be called.Titanium.App.addEventListener(event_one,function(e){ The open and focus Window event! messageLabel.text = app.js: event one, array listeners, for instance, must be definedlength = + e.data.length; before the window is opened.! messageWin.open();! setTimeout(function()! {! ! messageWin.close({opacity:0,duration:500}); Evaluating events as late as possible! },1000); can significantly improve application}); responsiveness. 9
    • 10. Ti.UITi.UI Ti.UI.ProgressBarTi.UI.2DMatrix Ti.UI.ScrollViewTi.UI.3DMatrix Ti.UI.ScrollableView Ti.UI.iPad.DocumentViewerTi.UI.ActivityIndicator Ti.UI.SearchBar Ti.UI.iPad.PopoverTi.UI.AlertDialog Ti.UI.Slider Ti.UI.iPad.SplitWindowTi.UI.Android Ti.UI.Switch Ti.UI.iPhoneTi.UI.Animation Ti.UI.Tab Ti.UI.iPhone.ActivityIndicatorStyleTi.UI.Button Ti.UI.TabGroup Ti.UI.iPhone.AnimationStyleTi.UI.ButtonBar Ti.UI.TabbedBar Ti.UI.iPhone.NavigationGroupTi.UI.Clipboard Ti.UI.TableView Ti.UI.iPhone.ProgressBarStyleTi.UI.CoverFlowView Ti.UI.TableViewRow Ti.UI.iPhone.RowAnimationStyleTi.UI.DashboardItem Ti.UI.TableViewSection Ti.UI.iPhone.ScrollIndicatorStyleTi.UI.DashboardView Ti.UI.TextArea Ti.UI.iPhone.StatusBarTi.UI.EmailDialog Ti.UI.TextField Ti.UI.iPhone.SystemButtonTi.UI.ImageView Ti.UI.Toolbar Ti.UI.iPhone.SystemButtonStyleTi.UI.Label Ti.UI.View Ti.UI.iPhone.SystemIconTi.UI.MaskedImage Ti.UI.WebView Ti.UI.iPhone.TableViewCellSelectionStyleTi.UI.MobileWeb Ti.UI.Window Ti.UI.iPhone.TableViewScrollPositionTi.UI.MobileWeb.NavigationGroup Ti.UI.iOS Ti.UI.iPhone.TableViewSeparatorStyleTi.UI.MobileWeb.TableViewSeparatorStyle Ti.UI.iOS.3DMatrix Ti.UI.iPhone.TableViewStyleTi.UI.Notification Ti.UI.iOS.AdViewTi.UI.OptionDialog Ti.UI.iOS.CoverFlowViewTi.UI.Picker Ti.UI.iOS.TabbedBarTi.UI.PickerColumn Ti.UI.iOS.ToolbarTi.UI.PickerRow Ti.UI.iPad 10
    • 11. Ti.Map• Maps are available for iOS, Android,Mobile WEB• For Android you must obtain an AndroidMaps API Key from Google• For Mobile Web the default map provideris Google• iOS supports routes 11
    • 12. Ti.Mapvar atlantaParams = {! ! latitude:33.74511,! ! longitude:-84.38993,! ! title:"Atlanta, GA",! ! subtitle:Atlanta Braves Stadiumnfoo,! ! animate:true,! ! leftButton:../images/atlanta.jpg,! ! rightButton: Titanium.UI.iPhone.SystemButton.DISCLOSURE,! ! myid:3 // CUSTOM ATTRIBUTE THAT IS PASSED INTO EVENT OBJECTS! };var atlanta = Titanium.Map.createAnnotation(atlantaParams);...var presetAnnotations = [atlanta,apple];var mapview = Titanium.Map.createView({! mapType: Titanium.Map.STANDARD_TYPE,! region:{latitude:33.74511, longitude:-84.38993, latitudeDelta:0.5,longitudeDelta:0.5},! animate:true,! regionFit:true,! userLocation:true,! annotations:presetAnnotations});mapview.selectAnnotation(atlanta);win.add(mapview); 12
    • 13. Ti.Contacts• Used for accessing and modifying thesystem contacts address book.• On Android, contacts are currently read-only, and so methods such as createPersonandremovePerson are not supported. 13
    • 14. Ti.Mediavar contentURL = http://movies.apple.com/media/us/ipad/2010/tours/apple-ipad-video-us-20100127_r848-9cie.mov;if (Ti.Platform.name == android) {! contentURL = "http://dts.podtrac.com/redirect.mp4/twit.cachefly.net/video/aaa/aaa0033/aaa0033_h264b_640x368_256.mp4";}var activeMovie = Titanium.Media.createVideoPlayer({! url: contentURL,! backgroundColor:#111,! movieControlMode:Titanium.Media.VIDEO_CONTROL_DEFAULT, // SeeTIMOB-2802, which may change this property name! scalingMode:Titanium.Media.VIDEO_SCALING_MODE_FILL});win.add(activeMovie);activeMovie.addEventListener(complete,function(){! if (!windowClosed)! {! ! var dlg = Titanium.UI.createAlertDialog({title:Movie,message:Completed!});! ! if (Ti.Platform.name === "android") {! ! ! win.close();! ! ! dlg.show();! ! } else {! ! ! dlg.show();! ! ! win.close();! ! }! }}); 14
    • 15. Ti.Media.VideoPlayervar vidWin = Titanium.UI.createWindow({ title : Video View Demo, backgroundColor : #fff});var videoPlayer = Titanium.Media.createVideoPlayer({ top : 2, autoplay : true, backgroundColor : blue, height : 300, width : 300, mediaControlStyle : Titanium.Media.VIDEO_CONTROL_DEFAULT, scalingMode : Titanium.Media.VIDEO_SCALING_ASPECT_FIT});videoPlayer.url = movie.mp4;vidWin.add(videoPlayer);vidWin.open(); 15
    • 16. Ti.FacebookThe top level Facebook module.The Facebook module is used for connecting yourapplication with Facebook. This module supports thefollowing features: • Logging in to Facebook and authorizing your application. • Making requests through the Facebook Graph API using requestWithGraphPath. • Making requests through the legacy Facebook REST API using request. • Posting Facebook dialogs. 16
    • 17. Ti.Facebook: login// Dont forget to set your appid and requested permissions, else the login button// wont be effective.Ti.Facebook.appid = [your appid];Ti.Facebook.permissions = [publish_stream];Ti.Facebook.addEventListener(login, function(e) { if (e.success) { alert(Logged in); }});Ti.Facebook.addEventListener(logout, function(e) { alert(Logged out);});// Add the button. Note that it doesnt need a click event listener.win2.add(Ti.Facebook.createLoginButton({ top : 50, style : Ti.Facebook.BUTTON_STYLE_WIDE})); 17
    • 18. Ti.Facebook: events// First make sure this permission existsTi.Facebook.permissions = [create_event];Ti.Facebook.authorize();// ...// Now create the event after youve confirmed authorize() was successful.var starttime = new Date(2012, 4, 31, 17, 0);var endtime = new Date(2012, 4, 31, 19, 0);var title = "Barrys Birthday Celebration";var description = "Barry will have a great party";var data = { start_time: JSON.stringify(starttime), end_time: JSON.stringify(endtime), summary: description, name: title};Ti.Facebook.requestWithGraphPath(me/events, data, POST, function(e) { if (e.success) { alert("Success! Returned from FB: " + e.result); } else { if (e.error) { alert(e.error); } else { alert("Unknown result"); } }}); 18
    • 19. Ti.GeolocationThe Geolocation module is used for accessing devicelocation based information.This module combines two sets of features: • Location services. Determining the location of the device • Geocoding and reverse geocoding. Converting geographic coordinates into addresses, and converting addresses into geographic coordinates.Getting Location InformationThere are two ways to get location information: • Make a one-time request with getCurrentPosition. • Register to receive location updates by adding an event listener for the location event. 19
    • 20. Ti.Geolocation: Position // GET CURRENT POSITION - THIS FIRES ONCE Titanium.Geolocation.getCurrentPosition(function(e) { if (!e.success || e.error) { currentLocation.text = error: + JSON.stringify(e.error); Ti.API.info("Code translation: "+translateErrorCode(e.code)); alert(error + JSON.stringify(e.error)); return; } var longitude = e.coords.longitude; var latitude = e.coords.latitude; var altitude = e.coords.altitude; var heading = e.coords.heading; var accuracy = e.coords.accuracy; var speed = e.coords.speed; var timestamp = e.coords.timestamp; var altitudeAccuracy = e.coords.altitudeAccuracy; Ti.API.info(speed + speed); currentLocation.text = long: + longitude + lat: + latitude; Titanium.API.info(geo - current location: + new Date(timestamp) + long + longitude + lat + latitude + accuracy + accuracy); }); 20
    • 21. Ti.Geolocation: geocodingvar addr = "2065 Hamilton Avenue San Jose California 95125";Titanium.Geolocation.forwardGeocoder(addr,function(evt){! Ti.API.info(in forward );! forwardGeo.text = "lat:"+evt.latitude+", long:"+evt.longitude;! Titanium.Geolocation.reverseGeocoder(evt.latitude,evt.longitude,function(evt)! {! ! if (evt.success) {! ! ! var text = "";! ! ! for (var i = 0; i < evt.places.length; i++) {! ! ! ! text += "" + i + ") " + evt.places[i].address + "n";! ! ! }! ! ! Ti.API.info(Reversed forward: +text);! ! }! ! else { .....! ! }! });}); 21
    • 22. Ti.NetworkThe Network module is used to access networkingrelated functionality.Ti.Network.BonjourBrowserTi.Network.BonjourServiceTi.Network.TCPSocket (*)Ti.Network.HTTPClientTi.Network.SocketTi.Network.Socket.TCPThe legacy Titanium.Network.TCPSocket object is stillrequired by the BonjourBrowser and BonjourServiceobjects. 22
    • 23. Ti.Network.HTTPClientHTTP client object that (mostly) implements theXMLHttpRequest specification.Use Titanium.Network.createHTTPClient to create anew HTTPClient object.An HTTPClient object is intended to be used for a singlerequest. It may be possible to re-use an HTTPClientobject, but this use case is not tested.There are three steps in making a typical HTTP request: • Creating an HTTPClient object. • Opening the HTTPClient object. • Sending the request.Before opening the request, you must define one ormore callbacks to handle the HTTP response, as well aserrors, progress updates, and other conditions. 23
    • 24. Ti.Network.HTTPClientvar url = "http://www.appcelerator.com";var client = Ti.Network.createHTTPClient({// function called when the response data is availableonload : function(e) { Ti.API.info("Received text: " + this.responseText); alert(success);},// function called when an error occurs, including a timeoutonerror : function(e) { Ti.API.debug(e.error); alert(error);},timeout : 5000 // in milliseconds});// Prepare the connection.client.open("GET", url);// Send the request.client.send(); 24
    • 25. Ti.DatabaseDatabase Management (SQLite)install(String path, String dbName)Installs an SQLite database to devices internal storage.Copies an SQLite database file to the devices internal storage (only)and creates a persistent name that is available for the lifetime of theapp. On Android, if the source file does not exist, an empty databaseis created.Returns a reference to the opened database. If the destination filealready exists, behaves as open.Files stored in the Private Documents directory on iOS5 will beautomatically backed up to iCloud and removed from the device inlow storage situations. 25
    • 26. Ti.DatabaseDatabase Management (SQLite)open(String path, String dbName)Opens an SQLite database.Opens an SQLite database and returns a reference to it. If thedatabase does not exist, creates an empty database file and returns areference to this opened database.Always close the database after use. 26
    • 27. Ti.Database var db = Ti.Database.open(mydb1Installed); db.execute(CREATE TABLE IF NOT EXISTS people (name TEXT, phone_number TEXT, city TEXT)); db.execute(DELETE FROM people); var thisName = Arthur; var thisPhoneNo = 1-617-000-0000; var thisCity = Mountain View; db.execute(INSERT INTO people (name, phone_number, city) VALUES (?, ?, ?), thisName, thisPhoneNo,thisCity); var personArray = [Paul,020 7000 0000, London]; db.execute(INSERT INTO people (name, phone_number, city) VALUES (?, ?, ?), personArray); var rows = db.execute(SELECT rowid,name,phone_number,city FROM people); db.close(); Ti.API.info(Row count: + rows.rowCount); var fieldCount; // fieldCount is a property on Android. if (Ti.Platform.name === android) { fieldCount = rows.fieldCount; } else { fieldCount = rows.fieldCount(); } Ti.API.info(Field count: + fieldCount); while (rows.isValidRow()){ Ti.API.info(Person ---> ROWID: + rows.fieldByName(rowid) + , name: + rows.field(1) + ,phone_number: + rows.fieldByName(phone_number) + , city: + rows.field(3)); rows.next(); } rows.close(); 27
    • 28. ...and many others... 28
    • 29. Ti.CloudAppcelerator Cloud Services (ACS) provides a wide array ofautomatically-scaled data storage and web services, such as userlogins, photo uploads, checkins, status updates, and pushnotifications, without the need to learn multiple third-party SDKsor do any server-side programming.This module is not included in the Titanium namespace, but it isbundled with the Titanium SDK as of version 2.0.0. To use it, itmust be registered like this:var Cloud = require(ti.cloud); 29
    • 30. External ModulesModules enable you extend Titaniumscore functionality.Modules add support for device-specific hardware or operating systemfunctionality.Modules also wrap native SDKs withTitanium-friendly JavaScript APIs tomake them easier to implement withinyour apps. 30
    • 31. 1) tiapp.xml ti.admob<module version="1.0">ti.admob</module>2) declare the modulevar admob = require(ti.admob);3) use the modulevar adview = admob.createView({ top:0, testing:true, adBackgroundColor:black, primaryTextColor:blue, secondaryTextColor:green, publisherId:<< your ID>> // Replace this string with your own API key!});win.add(adview);more samples here: https://github.com/appcelerator/Documentation-Examples 31
    • 32. ResourcesThis work is based upon the official Titanium docs• http://docs.appcelerator.com/titanium/2.0/index.html• http://docs.appcelerator.com/titanium/2.1/#!/api 32
    • 33. About me• @alessioricco• http://www.slideshare.net/alessioricco• http://itunes.apple.com/app/twinsmatcher/id429890747?mt=8• http://www.linkedin.com/in/alessioricco 33

    ×