In this chapter, we will cover:
Setting up the Android-based development environment
Setting up the iOS-based development environment
Setting up the Blackberry-based development environment
Setting up the browser-based development environment
Setting up the production environment
Detecting your device
Finding information about features that are supported in the current environment
Initializing your application
Letting your application configure itself using profiles
Responding to the orientation change
Like any other development, the first and foremost thing which is required, before we embark on our journey, is setting up the right environment so that the development, deployment, and testing becomes easy and effective. Moreover, this calls for a list of tools which are appropriate in this context. In this chapter, we will cover the topics related to setting up the environment using the right set of tools. Sencha Touch works on Android, iOS, and Blackberry platforms. For each of these platforms, we will see what steps we need to follow to set up the complete development and deployment environment. We will be packaging our Sencha Touch-based application using PhoneGap. PhoneGap is another JavaScript framework which provides the following two important capabilities:
The APIs needed to access the device features such as camera, address book, and so on.
A build mechanism for writing the code once (in the form of JS, HTML, CSS) and packaging them for different platforms such as iOS, Android, and so on.
Throughout the book, we will be using the following software:
Before we get any further, you should download and install the following, which will act as a common base for all our discussions:
Sun JDK 1.5 or above
Eclipse 3.3 or above
Sencha Touch 1.1.0 library
After downloading the Sencha Touch library, extract it to a folder, say c:\sencha-touch
. When you extract the folder, you would see the folders as shown in the following screenshot:

There are many files, however, which are not required for development and testing.
Note
The docs
folder contains the documentation for the library and is very handy when it comes to referring to the properties, configs, methods, and events supported by different classes. You may want to copy it to a different folder, so that you can refer to the documentation whenever needed.
Delete the files and folders which are enclosed within the rectangles as shown in the following screenshot:

This prepares us to get started. As Sencha Touch is a JavaScript library, you may want to configure your Eclipse installation for JavaScript development. You may install the Spket plug-in and configure it for Sencha Touch development. Steps to do so are detailed on the Spket website (http://spket.com/) and hence have been excluded from this book.
This recipe describes the detailed steps we shall follow to set up the environment for the Android-based development. The steps do not include setting up the production environment, which are detailed in a different recipe.
Before you begin, check that JDK is installed and the following environment variables are set correctly:
JAVA_HOME
PATH
Carry out the following steps:
Download and install Android SDK from the following URL: http://developer.android.com/sdk/index.html.
Download and install Eclipse ADT Plugin from the following URL:http://developer.android.com/sdk/eclipse-adt.html#installing.
Download and install PhoneGap from http://www.phonegap.com.
Launch Eclipse, click on the File menu, and select New | Android Project. Fill in the details, as shown in the following screenshot, and click on the Finish button:
In the root directory of the project, create two new directories:
libs
: To keep the third party jar that we will be using. In this case, we will keep the PhoneGap jar in itassets/www
: This is the default folder the SDK expects to contain the complete set of JS, CSS, and HTML files
Copy
phonegap.1.0.0.js
from your PhoneGap downloaded earlier toassets/www
.Copy
phonegap.1.0.0.jar
from your PhoneGap downloaded earlier tolibs
.Copy the
xml
folder from theAndroid
folder of your PhoneGap downloaded earlier to theres
folder.Make the following changes to
App.java
, found in thesrc
folder in Eclipse:Change the class extend from
Activity
toDroidGap
Replace the
setContentView()
line withsuper.loadUrl("file:///android_asset/www/index.html");
Add
import com.phonegap.*;
Right-click on the
libs
folder and select Build Paths | Configure Build Paths. Then, in the Libraries tab, addphonegap-1.0.0.jar
to the Project. You may have to refresh the project (F5) once again.Right-click on
AndroidManifest.xml
and select Open With | Text Editor.Paste the following permissions under
versionName
:<supports-screensandroid:largeScreens="true"android:normalScreens="true"android:smallScreens="true"android:resizeable="true"android:anyDensity="true"/> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.ACCESS_NETWOvRK_STATE" />
Tip
Downloading the example code for this book
You can download the example code files for all Packt books you have purchased from your account at www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
Add
android:configChanges="orientation|keyboardHidden"
to the activity tag inAndroidManifest
.Move the
c:\sencha-touch
folder to theassets/www
directory.Create and open a new file named
ch01_01.js
in theassets/www/ch01
directory. Paste the following code into it:Ext.setup({ onReady: function() { Ext.Msg.alert("INFO", "Welcome to the world of Sencha Touch!"); } });
Now create and open a new file named
index.html
in theassets/www
directory and paste the following code into it:<!DOCTYPE HTML> <html> <head> <title>Yapps! - Your daily applications!</title> <link rel="stylesheet" href="sencha-touch/resources/css/sencha-touch.css" type="text/css"> <script type="text/javascript" charset="utf-8" src="phonegap.1.0.0.js"></script> <script type="text/javascript" charset="utf-8" src="sencha-touch/sencha-touch-debug.js"></script> <script type="text/javascript" charset="utf-8" src="ch01/ch01_01.js"></script> </head> <body></body> </html>
Deploy to Simulator:
Right-click on the project and go to Run As and click on Android Application
Eclipse will ask you to select an appropriate AVD (Android Virtual Device). If there is not one, then you will need to create it. In order to create an AVD, follow these steps:
In Eclipse, go to Window | Android SDK and AVD Manager
Select Virtual Devices and click on the New button
Enter your virtual device details, for example, the following screenshot shows the virtual device details for the Samsung Galaxy Ace running Android 2.2:
Deploy to Device:
Make sure USB debugging is enabled on your device and plug it into your system. You may enable it by going to Settings | Applications | Development
Right-click on the project, go to Run As, and click on Android Application. This will launch the Android Device Chooser window
Select the device and click on the OK button
With the preceding steps, you will be able to develop and test your application.
In steps 1 through 3, we downloaded and installed Android SDK, its Eclipse plugin, and PhoneGap, which are required for the development of the Android-based application. The SDK contains the Android platform-specific files, an Android emulator, and various other tools required for the packaging, deployment, and running of Android-based applications. The ADT plugin for Eclipse allows us to create Android-based applications, build, test, and deploy them using Eclipse.
In step 4, we created an Android 2.2 project by using the ADT plugin.
In steps 5 through 12, we created the required folders and kept the files in those folders, and updated some of the files to make this Android project a PhoneGap-based Android project. In step 5, we created two folders: libs
and assets\www
. The libs
folder is where the PhoneGap and other third party libraries (JAR files) need to be kept. In our case, we only had to put in the PhoneGap JAR file (step 7). This JAR contains the PhoneGap implementation, which takes care of packaging the application for the target device (in this case, Android). The www
folder is where the complete application code needs to be kept. PhoneGap will use this folder to create the deployment package.
In step 6, we copied the PhoneGap's JavaScript file which contains the implementation of the PhoneGap APIs. You will do this if you intend to use the PhoneGap APIs in your application (for example, to get the contacts list in your application).
Note
For this book, this is an optional step. However, interested readers may find details about the API at the following URL: http://docs.phonegap.com/en/1.0.0/index.html.
In steps 8 and 9, we added the PhoneGap JAR file to our project's Build Path, so that it becomes available for the application development (and takes care of the compilation errors).
Then, in steps 10 through 13, we made changes to the manifest file to add the required application privileges, for example, access to the phone book, access to the phone status, and so on, when it is run on the Android 2.2 platform. You may learn more about the content of the manifest file and each of the elements that we added to it by referring to http://developer.android.com/guide/topics/manifest/manifest-intro.html.
In step 14, we moved the Sencha Touch library files to the www
folder, so that they are included in the package. This is required to run Touch-based applications.
In step 15, we created the ch01_01.js
JavaScript file, which contains the entry point for our Sencha Touch application. We have used the Ext.setup
API. The important property is onReady
, which is a function that Ext.setup
registers to invoke as soon as the document is ready.
In step 16, we modified the index.html
to include the Sencha Touch library related JavaScript: sencha-touch-debug.js
and CSS file: sencha-touch.css
, and our application specific JavaScript file: ch01_01.js
. The sencha-touch-debug.js
file
is very useful during development as it contains the nicely formatted code which can be used to analyze the application errors during development. You also need to include the PhoneGap JS file, if you intend to use its APIs in your application. The order of inclusion of the JavaScript and CSS files is PhoneGap | Sencha Touch | Application specific files.
In step 17, we created an Android Virtual Device (an emulator), and deployed and tested the application on it.
Finally, in step 18 we deployed the application on a real Android 2.2 compatible device.
This recipe outlines the steps to set up the environment for the iOS-based (for example, iPhone, iPad, iPod) development.
JDK is installed and the following environment variables are set correctly:
JAVA_HOME
PATH
You should have created the ch01_01.js
file as mentioned in the previous recipe.
Carry out the following steps:
Download and install Xcode from Apple Developer Portal (http://developer.apple.com). This requires you to have membership of the iOS and Mac developer programs.
Download the copy of
PhoneGap-1.0.0
and extract its contents. Navigate to theiOS
directory and run the installer until completion.Launch Xcode, and under the File menu, select New and then New Project. Name the new project
SenchaTouch
.Select PhoneGap-based Application from the list of templates.
Click on the Next button. Fill in the Product Name and Company Identifier for your application.
Choose a directory in which to store your application.
You should see your project in Xcode 4 now. Click on the Run button at the top-left corner. Your build should succeed and launch in the simulator.
You should see an error in your simulator informing you that
index.html
was not found.In order to fix this, we need to copy the
www
directory into the project. Right-click on the project in the left navigation window and click on Show in finder.In Finder, you should see the
www
directory beside your project.Drag the
www
folder into Xcode 4.Move the
C:\sencha-touch
folder towww
.After you drag, you should see a prompt with a few options. Make sure to select Create folder references for any added folders and click on Finish.
Add the
ch01
folder towww
and copy thech01_01.js
file, which was created in the previous recipe, inside it.Open the folder named
www
and paste the following code inindex.html
:<!DOCTYPE HTML> <html> <head> <title>Yapps! - Your daily applications!</title> <link rel="stylesheet" href="sencha-touch/resources/css/sencha-touch.css" type="text/css"> <script type="text/javascript" charset="utf-8" src="phonegap.1.0.0.js"></script> <script type="text/javascript" charset="utf-8" src="sencha-touch/sencha-touch-debug.js"></script> <script type="text/javascript" charset="utf-8" src="ch01/ch01_01.js"></script> </head> <body></body> </html>
Deploy to Simulator:
Make sure to change the Active SDK in the top-left menu to Simulator+version#
Click on Run in your project window header
Deploy to Device:
Open
SenchaTouch-Info.plist
and changeBundleIdentifier
to the identifier provided by Apple. If you have a developer license, then you can access and run the Assistant at http://developer.apple.com/iphone/manage/overview/index.action and register your App.Make sure to change the Active SDK in the top left menu to Device+version#.
Click on Run in your project window header.
In steps 1 and 2, we downloaded and installed XCode and other required tools and libraries. XCode is the IDE provided by Apple for the iOS-based application development.
In steps 3 through 6, we created a PhoneGap-based iOS project, using XCode.
In steps 7 through 14, we prepared the www
folder for the application. Its contents are described in the Setting up the Android-based development environment recipe.
In step 15, we included the Sencha Touch related files and the application specific JS file—ch01_01.js
—in index.html
.
In steps 16 and 17, we deployed and tested the application in the simulator, as well as a real iOS device, such as iPhone.
So far, we have seen how to set up the environments for Android and iOS development. This recipe walks us through the steps required to set up the environment for Blackberry-based development.
JDK is installed and the following environment variables are set correctly:
JAVA_HOME
PATH
Carry out the following steps:
Download and extract Apache Ant and add it to your
PATH
variable.Download BlackBerry WebWorks SDK from http://na.blackberry.com/eng/developers/browserdev/widgetsdk.jsp and install to, say,
C:\BBWP
.Open a command window and navigate to the
C:\BBWP
directory.Type
ant create -Dproject.path=C:\Touch\BlackBerry\WebWorks\book
and press Enter.Change to the newly created directory located at
C:\Touch\BlackBerry\WebWorks\book
.Open the
project.properties
file in your favorite editor and change the linebbwp.dir=
tobbwp.dir=C:\\BBWP
.Copy
C:\sencha-touch
to thewww
folder.Create the
ch01
folder insidewww
and copych01_01.js
, which was created in the first recipe, into thech01
folder.Edit
index.html
and past the following code:<!DOCTYPE HTML> <html> <head> <title>Yapps! - Your daily applications!</title> <link rel="stylesheet" href="sencha-touch/resources/css/sencha-touch.css" type="text/css"> <script type="text/javascript" charset="utf-8" src="phonegap.1.0.0.js"></script> <script type="text/javascript" charset="utf-8" src="sencha-touch/sencha-touch-debug.js"></script> <script type="text/javascript" charset="utf-8" src="ch01/ch01_01.js"></script> </head> <body></body> </html>
Build the PhoneGap sample project by typing
ant build
in your command window while you are in your project's directory.Deploy to Simulator:
While in your project directory, in command prompt, type
ant load-simulator
Press the BlackBerry button on the simulator, go to downloads and you should see your app loaded there
Deploy to Device:
You have to have your signing keys from RIM
While in your project directory, in the command prompt, type
ant load-device
Press the BlackBerry button on the simulator, go to downloads and you should see your app loaded there
In steps 1 and 2, we downloaded and installed the Blackberry SDK and PhoneGap required for Blackberry-based development.
In steps 3 through 6, we created a PhoneGap-based project for Blackberry.
In steps 7 through 9, we prepared the www
folder by creating and copying our application specific folders and files.
In step 10, we built the project. In addition, we modified index.html
to make it look exactly like the one created in the Setting up the Android-based development environment recipe.
In steps 11 and 12, we deployed and tested the application in the simulator, as well as in the real Blackberry device.
In the previous recipes, we saw how we can make use of PhoneGap to build, package, and deploy the Sencha Touch applications directly on the device. Another very popular kind of application is the browser-based one. All the devices which Sencha Touch supports come along with Internet browsers. In this recipe, we will see how we can develop a Sencha Touch application, access it, and test it using Internet browsers.
Sencha Touch is moving towards using HTML5 features but, today, it heavily uses the WebKit engine and, hence, in order to test the applications, we will require a browser which runs on the WebKit engine—Opera, Safari, and Chrome. We can also test most of the things on a browser running on your desktop/workstation (except things such as orientation changes).
Note
Sencha Touch applications do not work on browsers using the Gecko engine, which includes Mozilla Firefox.
We will be using this environment for this book to demonstrate the capabilities of Sencha Touch.
Make sure that your device has a WebKit compatible browser—Opera, Safari, or Chrome.
Verify that you have your GPRS or Wi-Fi enabled and working on your device, so that you are able to access the Internet.
You should have a web server such as Apache or Nginx deployed on a server, which is accessible on the Internet. For example, I have my web server running on http://walkingtree.in.
Carry out the following steps:
Create a folder named
touch
in your web server'sdeployment
/root
folder, for example,public_html
orhtdocs
.Copy the content of the
assets\www
folder, prepared in the Setting up the Android-based development environment recipe, to thetouch
folder. After copying, thetouch
folder should have the following files:Remove
phonegap-1.0.0.js
fromindex.html
.Go to the Internet browser on your device and enter the URL:
http://<your domain or ip address>:<port>/touch
(for example, http://walkingtree.in/touch) in the address bar and hit Go. You should have the application running inside the browser.
In step 1, we created the touch
folder as a placeholder to keep our application code inside it. This would help us avoid polluting the web server's root
folder.
In step 2, we copied the contents from the assets\www
folder, which we prepared in the Setting up the Android-based development environment recipe. In step 3, we removed the <script>
tag including the PhoneGap JS file, as we are not going to use its APIs in this book. Finally, in step 4, we accessed the application from a browser.
This recipe describes the steps required to create a production-ready package of the application. These steps are mentioned for the Sencha Touch-related applications; however, they can also be applied to any JavaScript-based application.
Make sure that you have completed the steps outlined in the Setting up the browser-based development environment recipe.
Carry out the following steps:
Trim down the Sencha Touch library by deleting the files and folders which are not required in the production environment. The following screenshot shows the files and folders which should be deleted from the
sencha-touch
folder:Update the
index.html
file to includesencha-touch.js
in place ofsencha-touch-debug.js
.Merge and minify your JavaScripts and CSS files. You may use the tool of your choice. Say you have created
yapps-all.js
(for now, it contains only thech01_01.js
) andyapps-all.css
(this may contain the mergedsencha-touch.css
and any of our application-specific CSS file, say,yapps.css
) as the merged and minified JavaScripts and CSS files, respectively.Note
Sencha uses and recommends JSBuilder and YUI Compressor and you can read more about this at the following URL:http://www.sencha.com/products/jsbuilder.
Remove the inclusion of the individual application-specific JavaScript files and CSS files from
index.html
.Include
yapps-all.js
andyapps-all.css
.Deploy the application on your production server.
In step 1, we removed the unwanted folders and files which are not required for a typical production deployment.
In step 2, we replaced the debug version of the library with the production ready version, which is a compressed and minified version of the debug version. This file will not have the comments and also the code is obfuscated.
In step 3, we merged all the JS/CSS files into one single file and minified them. You may want to find out the best way to combine the files. This is generally done to load the application quickly. You may choose to combine one or more files into one or create individual minified files. It is totally based on your project design and code structure.
In steps 4 and 5, we removed the individual inclusion of the JS and CSS files from index.html
and included the merged and minified ones. This recipe does not show the PhoneGap-related JS file. However, if your application is using it, then make sure that you also minify it, as the default one is not the production ready file.
Different devices offer different capabilities and hence for an application developer, it becomes important to identify the exact device, so that it can respond to the events in the most appropriate way. This recipe describes how we can detect the device on which the application is being run.
Carry out the following steps:
Create and open a new file
ch01_02.js
in thech01
folder and paste the following code into it:Ext.setup({ onReady: function() { if (Ext.is.Android) Ext.Msg.alert("INFO", "Welcome Android user!"); if (Ext.is.Blackberry) Ext.Msg.alert("INFO", "Welcome Blackberry user!"); if (Ext.is.iPad) Ext.Msg.alert("INFO", "Welcome iPad user!"); } });
Remove the following line from
index.html
:<script type="text/javascript" charset="utf-8" src="ch01/ch01_01.js"></script>
Include the following line in
index.html
:<script type="text/javascript" charset="utf-8" src="ch01/ch01_02.js"></script>
Deploy and run the application. Based on the device on which the application is being run, you will see a corresponding message.
The Ext.is
class is instrumental in detecting the target device on which your application is being run. It uses the JavaScript's navigator
object to detect the browser details, including the platform/device. For example, if the platform
property in the navigator
object has iPhone
in it, then the target platform is iPhone, whereas if the userAgent
property in the navigator
object has Android
, then the platform is Android.
Each device and platform offers a rich set of functionality. However, it is difficult to identify a set of features which are available across devices and platforms. In addition, even if we happen to find out the list of common features, there may be reasons where you may want to use a feature on a device which is not present on other devices and you would make your application work on those devices by performing the best approximation of that specific feature. For example, on a device if SVG is supported, you may want to make use of that feature in your application to render images using it, so that they are scalable. However, if another device does not support SVG, you may want to fall back to rendering your image into JPEG/PNG, so that the image will be visible to the user. This recipe describes how an application can detect the different features that a device supports. This comes in very handy to enable/disable certain application features based on the device-supported features.
Carry out the following steps:
Create and open a new file named
ch01_03.js
in thech01
folder and paste the following code into it:Ext.setup({ onReady: function() { var supportedFeatures = "Ext.supports.AudioTag : " + (Ext.supports.AudioTag ? "On" : "Off"); supportedFeatures += "\nExt.supports.CSS3BorderRadius : " + (Ext.supports.CSS3BorderRadius ? "On" : "Off"); supportedFeatures += "\nExt.supports.CSS3DTransform : " + (Ext.supports.CSS3DTransform ? "On" : "Off"); supportedFeatures += "\nExt.supports.CSS3LinearGradient : " + (Ext.supports.CSS3LinearGradient ? "On" : "Off"); supportedFeatures += "\nExt.supports.Canvas : " + (Ext.supports.Canvas ? "On" : "Off"); supportedFeatures += "\nExt.supports.DeviceMotion : " + (Ext.supports.DeviceMotion ? "On" : "Off"); supportedFeatures += "\nExt.supports.Float : " + (Ext.supports.Float ? "On" : "Off"); supportedFeatures += "\nExt.supports.GeoLocation : " + (Ext.supports.GeoLocation ? "On" : "Off"); supportedFeatures += "\nExt.supports.History : " + (Ext.supports.History ? "On" : "Off"); supportedFeatures += "\nExt.supports.OrientationChange : " + (Ext.supports.OrientationChange ? "On" : "Off"); supportedFeatures += "\nExt.supports.RightMargin : " + (Ext.supports.RightMargin ? "On" : "Off"); supportedFeatures += "\nExt.supports.SVG : " + (Ext.supports.SVG ? "On" : "Off"); supportedFeatures += "\nExt.supports.Touch : " + (Ext.supports.Touch ? "On" : "Off"); supportedFeatures += "\nExt.supports.Transitions : " + (Ext.supports.Transitions ? "On" : "Off"); supportedFeatures += "\nExt.supports.TransparentColor : " + (Ext.supports.TransparentColor ? "On" : "Off"); supportedFeatures += "\nExt.supports.VML : " + (Ext.supports.VML ? "On" : "Off"); Ext.Msg.alert("INFO", supportedFeatures); } });
Remove the following line from
index.html
:<script type="text/javascript" charset="utf-8" src="ch01/ch01_02.js"></script>
Include the following line in
index.html
:<script type="text/javascript" charset="utf-8" src="ch01/ch01_03.js"></script>
Deploy and run the application.
Check that the support for different features is encapsulated inside the Sencha Touch's Ext.supports
class. This class applies different mechanisms to find out whether a requested feature is supported by the target platform/device. For example, to find out whether the device supports touch, this class checks whether ontouchstart
is present in the window
object. Another example is, to find out whether SVG is supported on the target platform, it tries to add an SVG element (which it removes after successful creation and setting the flag to indicate that the device supports SVG) to the document
.
So far, we have been using Ext.setup
to enter into our application, where the entry point is provided by the onReady
method, which is invoked when the document is ready. However, in an enterprise setup, an application is much more complex and needs more configurations that that which Ext.setup
provides. For example, if you would like to configure your application with the history support, rather than doing it for individual pages or components, you may like your application to configure it based on the target platform and many more. These kinds of needs are addressed by Sencha Touch by providing a dedicated class.
Sencha Touch provides an
Ext.Application
class to create an application. This is a convenient way to create an application. Besides configuring your application, this class also allows you to structure your complete application in the form of Model-View-Controller and initialize it using a convenient method. The class allows the user to implement a function, which can be called when the application is launched. In this recipe, we will see how to create and initialize an application using the Ext.Application
class.
Carry out the following steps:
Create and open a new file
ch01_04.js
in thech01
folder and paste the following code into it:new Ext.Application({ name: 'MyApp', launch: function() { this.viewport = new Ext.Panel({ fullscreen: true, items : [ { html: 'Welcome to My App!' } ] }); } });
Remove the following line from
index.html
:<script type="text/javascript" charset="utf-8" src="ch01/ch01_03.js"></script>
Include the following line in
index.html
:<script type="text/javascript" charset="utf-8" src="ch01/ch01_04.js"></script>
Deploy and run the application.
Ext.Application
provides various configuration options, which can be specified while constructing the Application
instance. The name
property provides the application name, which is also used as the namespace for the application being initialized. In addition, by default, the following namespaces are registered using the name
property value:
MyApp.models
MyApp.views
MyApp.controllers
MyApp.stores
Another property is launch
. The launch
function creates the application's viewport and runs any actions the application needs to perform when it boots up. The launch
function is run once. In the preceding code, we are creating a panel in the full screen mode which will show Welcome to My App! in its body.
This recipe describes how you can set up multiple profiles for your application and let your application configure itself using the profile.
Carry out the following steps:
Create and open a new file named
ch01_05.js
in thech01
folder and paste the following code into it:new Ext.Application({ name: 'MyApp', profiles: { phoneBlackberry: function() { return Ext.is.Blackberry; }, phoneAndroid: function() { return Ext.is.Android; }, tabletPortrait: function() { return Ext.is.Tablet && Ext.orientation == 'portrait'; }, tabletLandscape: function() { return Ext.is.Tablet && Ext.orientation == 'landscape'; } }, launch: function() { this.viewport = new Ext.Panel({ fullscreen: true, items : [ { html: 'Welcome to My App!' + ' - profile - ' + this.getProfile(), } ] }); } });
Remove the following line from
index.html
:<script type="text/javascript" charset="utf-8" src="ch01/ch01_04.js"></script>
Include the following line in
index.html
:<script type="text/javascript" charset="utf-8" src="ch01/ch01_05.js"></script>
Deploy and run the application.
The Application
class provides a property named profiles
, which is used to set up multiple profiles, as shown in the preceding code. When the application is launched, each of the configured profile functions such as phoneBlackberry
, phoneAndroid
, and so on, is evaluated in the order of their definition. The first profile function that returns true is the one which becomes the profile of the application. For example, if we are running the application on the Android phone, then phoneAndroid
is the first function that will return true and, hence, the profile of the application will be set to phoneAndroid
.
The current profile can be fetched from the application or any component. You can use the getProfile()
method which returns the name of the profile, for example, phoneAndroid
.
The profile is applied, by default, at the time of the application launch.
There are few more interesting options and features that the Application
class provides to have a better control of the profiles and their application. Let's see what else can be done with the profiles.
As we saw, the profile is applied to the components at the time of application launch. It may not be desirable all the time. You may want to apply the profiles at a later stage in your application. For example, your application has a photo viewer which shows the photo on the left-hand side and the photo detail on the right-hand side of the page. Moreover, due to the layout, and to have a better view of the photo and its detail, say, you always want the user to switch to the landscape mode. In this case, you would like to wait until the user opens the viewer and that is when you would like to identify the profile and take action accordingly.
Applying the profile at the application launch time is controlled by the setProfilesOnLaunch
property. By default, this is set to true
. In your application initialization, you should pass the following additional config:
setProfilesOnLaunch : false
Therefore, the code would look something like this:
new Ext.Application({ name: 'MyApp', setProfilesOnLaunch: false, profiles: { ……..
By default, at the launch time, the current profile is applied to all the components of the application. If you do not want this to happen, then you will have to set autoUpdateComponentProfiles
to false
during your application initialization.
In some applications, you may want to ignore the effect of profile changes. To do so, we will have to implement the handler for the beforeprofilechange
event and return false
from it. The Application
class raises this event after it has detected the profile change and before it would start to apply the profile to the components. If false
is returned from the handler, it would not apply the profile to the components. The following code snippet shows how the handler needs to be written:
new Ext.Application({ name: 'MyApp', setProfilesOnLaunch: false, profiles: { …….. }, beforeprofilechange: function(profile, oldProfile) { return false; }
If you choose not to apply the profile at the time of launch, but defer it until the event of interest occurs, then you can achieve this by calling the determineProfile()
method of the Application
class. In addition, you will have to make sure that autoUpdateComponentProfiles
is set to true
before the method is called.
It is possible to change the orientation from portrait to landscape mode by turning your device. Many applications make use of this facility to provide better usability to the user. For example, when we are working with the virtual keyboard and change the orientation from portrait to landscape, the keyboard gets bigger and it becomes easier to type. Most of the devices support orientation changes and, based on your application, you may want to make use of this feature to change your application layout or behavior. Sencha Touch automatically watches for this and notifies all the application components by sending them the orientationchange
event. If the application or any component of it needs to change its behavior, then the corresponding component registers a handler for the orientationchange
event.
Carry out the following steps:
Create and open a new file named
ch01_06.js
in thech01
folder and paste the following code into it:new Ext.Application({ name: 'MyApp', profiles: { phoneBlackberry: function() { return Ext.is.Blackberry; }, phoneAndroid: function() { return Ext.is.Android; }, tabletPortrait: function() { return Ext.is.Tablet && Ext.orientation == 'portrait'; }, tabletLandscape: function() { return Ext.is.Tablet && Ext.orientation == 'landscape'; } }, launch: function() { this.viewport = new Ext.Panel({ fullscreen: true, listeners: { orientationchange : function( thisPnl, orientation, width, height ){ Ext.Msg.alert("INFO","Orientation: " + orientation + " : width:" + width + ":height:" + height); } }, items : [ { html: 'Welcome to My App!' + ' - profile - ' + this.getProfile(), } ] }); } });
Remove the following line from
index.html
:<script type="text/javascript" charset="utf-8" src="ch01/ch01_05.js"></script>
Include the following line in
index.html
:<script type="text/javascript" charset="utf-8" src="ch01/ch01_06.js"></script>
Deploy and run the application.
The Sencha Touch framework provides certain properties on the components, which directly affect the orientation change detection and notification. There are certain properties on the components based on which it derives whether the orientation change needs to be notified. The monitorOrientation
property on the component directly instructs the library whether it has to monitor for the orientation change. This property is, by default, set to false
—meaning, do not monitor for the orientation change. Hence, beforeorientationchange
and orientationchange
events will not be fired. However, the property fullscreen
affects the monitorOrientation
value. In the preceding code, fullscreen
has been set to true
, which sets the monitorOrientation
to true
and due to this, the library will monitor for the orientation change. When that happens, it fires the beforeorientationchange
and orientationchange
events. Any component which intends to handle the orientation change must implement the handler for these events.
On the container components (for example, Panel, TabPanel, and so on) enabling scrolling immediately sets the monitorOrientation
to true
.
Say, in your application, monitoring of the orientation change has been enabled, but some components neither want to handle the orientation change-related events, nor do they want the default behavior to be executed. In this case, these components will have to stop the orientation change and the subsequent section shows how to achieve that.