Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Mobile

213 Articles
article-image-android-30-application-development-gps-locations-and-maps
Packt
22 Jul 2011
7 min read
Save for later

Android 3.0 Application Development: GPS, Locations, and Maps

Packt
22 Jul 2011
7 min read
  Android 3.0 Application Development Cookbook Design and develop rich smartphone and tablet applications for Android 3.0         Introduction For managing location based information, Android provides the android.location package which in turn gives us the LocationManager class that gives us access to location based functions such as the latitude and longitude of a device's position. Tracking a device over time is made equally convenient and the LocationListener class monitors changes in location as they occur. Listening for location changes is only a part of the story, as Google provides APIs for managing Google Maps data and displaying and manipulating maps through the use of the MapView and MapController classes. These powerful tools require us to sign up with Google first, and once done enable us to zoom in and out of maps, pan to any location that we are looking for, and when we want to, include application information on a map, and even add our own layers to maps and mark locations on a Google map. Detecting a device's location Android locations are expressed in terms of latitude and longitude coordinates. The default format is degrees. The Location object can also be used to store a time-stamp and other information such as speed and distance traveled. Although obtaining a device's last known location does not always yield the most accurate information, it is often the first reading that we may want. It is fast, simple to employ, and makes a good introduction to the LocationManager. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> How to do it... Use the TextView provided in the main.xml file and give it a resource ID: android:id="@+id/text_view" Declare a TextView as a class-wide field in the Java activity code: TextView textView; Then, find it in the usual way, from within the onCreate() method: textView = (TextView) findViewById(R.id.text_view); Next, and still within onCreate(), declare and define our LocationManager: LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Then, to retrieve the last known location using GPS and display this in the text view, add these lines: Location loc = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER); textView.setText("latitude: " + loc.getLatitude() + "nlongitude: " + loc.getLongitude()); Run the code on a handset or emulator to obtain its location: How it works... The use of a LocationManager to obtain the device's last known location is very straightforward. As with other system services, we obtained it with getSystemService() and the getLastKnownLocation() method returns the Location object itself, which can be further queried to provide latitude and longitude coordinates. We could have done more with the Location object, for example Location.getAltitude() will return altitude and getDistance(Location) and getBearing(Location) will return distance and bearing to another Location. It is possible to send mock locations to an emulator using the DDMS perspective in Eclipse: Before sending location data this way, make sure that you have set the emulator to allow mock locations under Settings | Applications | Development. It is worth noting that although use of the getLastKnownLocation() method may not always be accurate, particularly if the device has been switched off for some time, it does have the advantage of yielding almost immediate results. There's more... Using GPS to obtain a location has a couple of drawbacks. Firstly, it does not work indoors; and secondly, it is very demanding on the battery. Location can be determined by comparing cell tower signal strengths, and although this method is not as accurate, it works well indoors and is much more considerate to the device's battery. Obtaining a location with a network provider The network provider is set up in exactly the same way as the previous GPS example, simply exchange the Location declaration with: Location loc = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); You will also need to change, or amend, the permission in the manifest file with: <uses-permission android_name="android.permission.ACCESS_COURSE_LOCATION" /> Listening for location changes Obtaining the last known location as we did in the previous recipe is all well and good and handy for retrieving a Location quickly, but it can be unreliable if the handset has been switched off or if the user is on the move. Ideally we want to be able to detect location changes as they happen and to do this we employ a LocationListener. In this recipe we will create a simple application that keeps track of a mobile device's movements. Getting ready This task can be performed most easily by starting where the previous one left off. If you have not completed that task yet, do so now—it is very short—then return here. If you have already completed the recipe then simply open it up to proceed. How to do it... First, move the declaration of our LocationManager so that it is a class-wide field: LocationManager manager; In the main Java activity code, before the TextView.setText() call, add the following three lines: LocationListener listener = new MyLocationListener(); manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 50, listener); Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Now create an inner class called MyLocationListener that implements LocationListener: LocationListener: public class MyLocationListener implements LocationListener { } Eclipse will most likely insist that you add some unimplemented methods and you should do so. For now, only complete one of them, the onLocationChanged() callback: @Override public void onLocationChanged(Location l) { textView.setText("/n/nlatitude: " + l.getLatitude() + "nlongitude: " + l.getLongitude()); } Leave the others as they are: @Override public void onProviderDisabled(String provider) {} @Override public void onProviderEnabled(String provider) {} @Override public void onStatusChanged(String provider, int status, Bundle extras) {} If you want to test this code on an emulator, then go right ahead. However, this code will create a serious drain on the battery of a handset, and it is wise to switch our listener off when it is not needed. Here we have used the activity's onPause() and onResume() functions to control this. You may wish to include these statements in any part of your activity's life cycle that suits your application's purpose: @Override protected void onResume() { super.onResume(); manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 50, listener); } @Override protected void onPause() { super.onPause(); manager.removeUpdates(this); } If you have not already tested this application, do so now. You will need to move around if you are testing it on a real device, or send mock locations to an emulator to see the code in action: How it works... In this recipe we used the LocationManager to provide location updates roughly every 30 seconds (30000 milliseconds) or whenever the location changed by more than 50 meters. We say 'roughly' because these values work only as a guide and the actual frequency of updates often varies from the values we set. Nevertheless, setting these two parameters of the requestLocationUpdates() method to high values can make a big difference to the amount of battery power the GPS provider consumes. Hopefully the use of the provider and the LocationListener as the other two parameters is self explanatory. The LocationListener operates very much as other listeners do and the purpose of the onProviderEnabled() and onProviderDisabled() should be clear. The onStatusChanged() method is called whenever a provider becomes unavailable after a period of availability or vice versa. The int, status can represent 0 = OUT_OF_SERVICE, 1 = TEMPORARILY_UNAVAILABLE, or 2 = AVAILABLE.  
Read more
  • 0
  • 0
  • 2329

article-image-rhomobile-faqs
Packt
21 Jul 2011
3 min read
Save for later

Rhomobile FAQs

Packt
21 Jul 2011
3 min read
  Rhomobile Beginner's Guide Step-by-step instructions to build an enterprise mobile web application from scratch         Read more about this book       (For more resources on this topic, see here.) Q: Does Rhomobile create a pure Native Application? A: Yes. Rhomobile creates a pure Native Application. This Application is similar to an Application available in i-store. This application can use device capabilities such as GPS, PIM contacts and calendar, camera, native mapping, push, barcode, signature capture, and Bluetooth. These are much faster than Browser-based applications.   Q: I am new to Ruby should I use Rhomobile? A: Although you need to know Ruby to write Rhodes applications, we realize that many folks learn both Ruby and Rhomobile at the same time. As Rhomobile products require an elementary level of Ruby knowledge, this will not affect your learning curve. But I recommend that you go to any Ruby tutorial online.   Q: Is Rhomobile Free? A: Rhodes is free and open source under MIT Licence. To use RhoSync, you must purchase a commercial license when development commences or you must open source your app under the GPL license. The pricing and details can be found at www.rhomobile.com.   Q: Is support available for Rhomobile? A: Yes. However, you have to purchase a Rhodes Enterprise License and the Rhodes Commercial License to get commercial support. Apart from the Rhomobile support, there are various webinars and tutorials available on www.rhomobile.com. Another good support resource is the Rhomobile Google group, where Rhomobile experts are there to help you.   Q: What about Rhomobile security? A: Both Rhodes and RhoSync support use of https as a transport. In fact it is easier with Rhodes than with native code. You just list the https URL and Rhodes will connect to the backend appropriately. This is simple in contrast to underlying SDKs where significantly different code is written to connect to an https URL.   Q: Does Rhomobile support HTML5? A: Yes, Rhomobile supports HTML5 tags provided the device you are targeting also supports them.   Q: Can we write unit test case for the code? A: Yes, we can write unit test case in Rhodes.   Q: Can we use Ruby gems with Rhodes? A: Yes, we can use Ruby gems with Rhodes. We have to include them in the Rhodes configuration file.   Q: Do we need to have knowledge of different device databases? A: No, we don't need to have prior knowledge of those databases, Rhodes will take care of this. We write our query using Object-relational mapping (ORM) called Rhom and it is the work of ORM to shape the query.   Summary In this article we saw some of the most frequently asked questions on Rhomobile. Further resources on this subject: An Introduction to Rhomobile [Article] Getting Started with Internet Explorer Mobile [Article] jQuery Mobile: Organizing Information with List Views [Article] jQuery Mobile: Collapsible Blocks and Theming Content [Article] Fundamentals of XHTML MP in Mobile Web Development [Article]
Read more
  • 0
  • 0
  • 1313

article-image-introduction-rhomobile
Packt
21 Jul 2011
6 min read
Save for later

An introduction to Rhomobile

Packt
21 Jul 2011
6 min read
The Rhomobile family Rhomobile Inc. is a computer software company that provides leading products for building the new generation of mobile applications. It offers an open-source Ruby-based mobile development framework for business mobility solutions through its four major products Rhodes, RhoSync, Rhohub, and RhoGallery. Rhodes Rhodes is an open source framework by Rhomobile. It develops native applications for almost all smart phones. The applications built through Rhodes are pure native applications and use device capabilities such as GPS, PIM contacts and calendar, camera, native mapping, push, barcode, signature capture, and Bluetooth. Rhodes accelerates the development of mobile applications without compromising on its portability. This framework is similar to the popular Rails framework. It is based on Model view Controller and has inbuilt Object Relational Manager (ORM) called Rhom that is similar to active Record in Rails. Most user interface customization can be done in HTML templates (ERB, eruby files). A single set of source written with Rhodes can be compiled to run across all of the supported smart phones. This means that we will have the same code base for all your devices. RhoSync RhoSync is a standalone mobile sync server that keeps enterprise application data up to date and available on users' smart phones. Enterprise apps require local synchronized data to be used most of the time. The information is stored locally on a users' device and is available to them even in offline mode. It is very easy to write a source adapter as RhoSync generates most of the code while creating the source adapter. The source adapter can also be used to Create, Read, Update, and Delete (CRUD) operations on a model. Rhosync uses Redis, which is a NoSql Key Value store for data caching. This makes Rhosync more scalable. RhoSync performs its push-based sync using the native smartphone push SDKs. It uses new advanced BlackBerry Enterprise Server and iPhone 3.0 SDKs for Push. It uses BES Push and iPhone Push for synchronization, allowing real-time updates of backend application information. RhoHub RhoHub is a hosted development environment for Rhodes and Rhosync. The RhoSync application will be deployed on the famous Ruby cloud Heroku with the interface of RhoHub. RhoHub enables git-powered source control and collaboration with your team. It allows us to directly build an application for different smart phones without installing SDKs. It makes the process of the build very smooth since we don't have to install any development toolkits. It is only a one click process that automatically creates a build for most of the smart phones. Rhohub provides us with the following functionalities: Creating a build for a Rhodes application Deploying the Rhosync application to the cloud Providing version control with git Managing collaborators RhoGallery RhoGallery provides a hosted mobile app management solution. It allows administrators to manage the set of apps exposed to their users. It also makes it easy for them to get mobile apps onto their devices. It enables users to launch all of their important enterprise apps from a single place. RhoGallery consists of a management console for "app galleries" on RhoHub, as well as a RhoGallery App that users load onto their devices. Even for an individual developer with one or a few apps, RhoGallery makes it easy to expose those apps to their users. RhoGallery handles inviting the users and determining the appropriate downloads to provide to them. RhoGallery provides the following functionalities: Administrator management of exposed apps to end users Central user launching of exposed apps Automatic provisioning of appropriate apps for end users Why Rhomobile is cutting edge The following features give a cutting edge to Rhomobile in mobile application development: Model View Controller: Most of the other frameworks available in the market are based on HTML and JavaScript. However, as Rhodes is a Ruby-based framework and its structure is similar to the popular framework Rails, it also supports Model View Controller, so code written with Rhodes is more structured and easy to understand. Cross Platform Support for All Devices: Rhodes supports the following devices: Android, Windows Mobile, BlackBerry, and iphone. The best thing is you have a single code base from which you can build applications for different smart phones. It does not work in a traditional way in that we have to write separate code for different types of phones. Offline Capabilities using Rhosync: Rhomobile supports local synchronization of data. As we can synchronize the data using Rhosync it provides offline Capabilities. It can work even if you are offline. Object Relational Manager: Rhodes provides an inbuilt Object Relational Manager called Rhom. It is similar to Active Record in Rails but with basic functionality only. It helps us to write queries without thinking about which database is being used by phone. Rapid Development: One of the most interesting features of Rhodes is that it imposes some fairly serious constraints on how you structure the applications that help us for rapid development. Rhomobile products are properly structured and well organized, which enforce us to do rapid development. Rhodes is very comfortable, familiar, and massively productive. Scalable Sync Server: The Sync Server uses a NoSql Database which makes it scalable. Specifically, it is the only sync server that has a built-in "no SQL" Redis key value store, making it more scalable than other sync servers which offer internal relational database servers for caching. RhoSync also performs its push-based sync using the native smart phone push SDKs, which no other sync server does. Liberal use of code generation: Rhodes/RhoSync can write a lot of code for you. For example, when you need a class to represent a table in your database, you don't have to write most of the methods. Rhodes even offers an application generator that creates an initial app based on the structure of your models or business objects in your app. It's very similar to the scaffolding offered by most modern web frameworks with basic list/create/read/update/delete objects functionality. For each basic CRUD action, views in HTML are also offered. You'll find that you're writing only a fraction of code compared to other frameworks. Metadata: Every enterprise application that is used to run a company's core business has a different schema for its business objects. For example, every application has a varying and customized structure that changes with time. It is not possible to install the client application again and again for a small change. The Metadata framework provides a way to handle the view from the Rhosync server. It also provides validation and a custom template. Hosted Development and Build: Rhomobile also provides a hosted management and Build through Rhohub. We can deploy a Rhosync app and build our Rhodes code for different phones with it.
Read more
  • 0
  • 0
  • 2004
Banner background image

article-image-how-use-jquery-mobile-grid-and-columns-layout
Packt
18 Jul 2011
6 min read
Save for later

How to Use jQuery Mobile Grid and Columns Layout

Packt
18 Jul 2011
6 min read
  jQuery Mobile First Look Discover the endless possibilities offered by jQuery Mobile for rapid Mobile Web Development Trying to communicate and provide information in an effective way can be a little trickier when we are targeting mobile devices; their screens are relatively small (ridiculously small if we think about our 24 inch iMac resting on our office desk), and we have already understood that we cannot display content in the way we used to, back in the days when desktop computers were the only way to access data on the Internet. With the advent of mobile browsing, new solutions had to be found. The jQuery Mobile framework provides a number of tools, widgets, and components which are extremely helpful in formatting our content and make it look elegant and put-together even on our beloved smaller-screen devices – well, especially for them! In fact, the difficulty in designing, formatting, and correctly showing a page on a mobile device is going to become a no-brainer using the set of elements jQuery Mobile provides in order to allow for an easy styling of our web application content. How content is displayed Yes, there is nothing wrong in just writing down what our website or web application is about in the HTML file. It's always worked and always will. The actual point here is taking advantage of the tools jQuery Mobile offers us to format our information, specifically for mobile devices. For example, there are occasions in which the need for multiple columns may arise: we can use a layout grid, which is nothing more than some CSS-based columns. Or, on a completely different note, we might just need to hide/show a block of content: collapsible blocks have been designed for this, and can be easily implemented in our site layout. But before we begin analyzing any of the methods in which we are able to format our content according to our liking, we should take a look at how content is displayed in its basic HTML formatting. Based upon the "light hand approach" (as they call it), jQuery Mobile lets the browser rendering take precedence over any other third-party styling, with exceptions made for the following little tweaks the framework applies to any page by default: Adding a bit of padding for a better readability Using the theming system to apply fonts and colors This particular approach to styling by default should make the designers really happy, as they often find themselves fighting with preset colors schemes, default fonts, weird margin, and padding values and usually end up resetting everything and starting again from scratch. Thankfully, the default padding value looks quite right and, as far as theming goes, we are able to easily customize (and create new) themes through CSS files and a theming framework which is extremely versatile and flexible. Default HTML markup styling So, what happens if we just write some HTML markup and want some text to be bold, emphasized, or hyper-linked? jQuery Mobile applies some basic styling to the elements and makes their look consistent with the simple and clean layout we have already seen in action. The following screenshot represents how headings and standard paragraphs are displayed and generated by the following code: <!DOCTYPE html> <html> <head> <title>Default HTML markup styling</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a2/ jquery.mobile-1.0a2.min.css" /> <script src="http://code.jquery.com/jquery-1.4.3.min.js"></script> <script src="http://code.jquery.com/mobile/1.0a2/jquery.mobile- 1.0a2.min.js"></script> </head> <body> <div data-role="page" id="home"> <div data-role="content"> <h1>H1 Heading</h1> <h2>H2 Heading</h2> <h3>H3 Heading</h3> <h4>H4 Heading</h4> <h5>H5 Heading</h5> <h6>H6 Heading</h6> <p>This is a paragraph. <strong>Lorem (bold)</strong> <em>ipsum (emphasized)</em> <a href="#">dolor (link)</a> sit amet, consectetur adipiscing elit.</p> <blockquote>Blockquote containing a <cite>cite</cite></ blockquote> <p>This is a paragraph. <strong>Lorem (bold)</strong> <em>ipsum (emphasized)</em> <a href="#">dolor (link)</a> sit amet, consectetur adipiscing elit.</p> </div> </div> </body> </html> The result is shown in the following screenshot: Similarly, the following code produces a preview of what lists and tables look like: <!DOCTYPE html> <html> <head> <title>Default HTML markup styling</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a2/ jquery.mobile-1.0a2.min.css" /> <script src="http://code.jquery.com/jquery-1.4.3.min.js"></script> <script src="http://code.jquery.com/mobile/1.0a2/jquery.mobile- 1.0a2.min.js"></script> </head> <body> <div data-role="page" id="home"> <div data-role="content"> <ul> <li>Unordered list item 1</li> <li>Unordered list item 2</li> <li>Unordered list item 3</li> </ul> <ol> <li>Ordered list item 1</li> <li>Ordered list item 2</li> <li>Ordered list item 3</li> </ol> <table> <caption>Table caption</caption> <thead> <tr> <th scope="col">Name</th> <th scope="col">City</th> <th scope="col">Phone</th> </tr> </thead> <tfoot> <tr> <td colspan="5">Table foot</td> </tr> </tfoot> <tbody> <tr> <th scope="row">David Green</th> <td>New York City, NY</td> <td>555-0123</td> </tr> <tr> <th scope="row">Martha White</th> <td>Los Angels, CA</td> <td>555-0188</td> </tr> <tr> <th scope="row">Bobby Brown</th> <td>Washington, D.C.</td> <td>555-0110</td> </tr> </tbody> </table> </div> </div> </body> </html>
Read more
  • 0
  • 0
  • 2277

article-image-jquery-mobile-collapsible-blocks-and-theming-content
Packt
18 Jul 2011
4 min read
Save for later

jQuery Mobile: Collapsible Blocks and Theming Content

Packt
18 Jul 2011
4 min read
jQuery Mobile First Look Discover the endless possibilities offered by jQuery Mobile for rapid Mobile Web Development          The reader would benefit by referring the previous article on How to Use jQuery Mobile Grid and Columns Layout. A note on collapsible blocks On a completely different note, jQuery Mobile provides an easy-to-use and visually-appealing solution to hide and show content, namely, the so-called collapsible blocks. Collapsible blocks should be already well-known to the web designers out there, and they have gained in popularity especially after the advent of JavaScript libraries and frameworks like jQuery, which have made writing the necessary code a matter of minutes to obtain a pane which shows its content once a button (or any kind of element, actually) is clicked. The following screenshot shows how jQuery Mobile renders, by default, any collapsible block we include into our web page: So, how do we create a (set of) collapsible block(s)? Collapsible blocks are obtained by assigning a container the data-role="collapsible" attribute. As easy as that. <div data-role="collapsible"> <!-- this is a collapsible block --> </div> The jQuery Mobile framework needs a heading element to be present inside the container. The heading (which can be from h1 through h6) will be styled like a clickable button, and a plus (+) symbol will be added to its left to indicate it's expandable. Once we click the header/button and the content shows, a minus (-) symbol will replace the plus to indicate it's collapsible. Where do I put the heading? The heading can be placed anywhere inside the container. Remember that jQuery Mobile will use as a header the very first h-element it finds inside the container, and remove it from its original position. Once the required header is provided, you can add any other h-element to the container and it will not be processed (that is, it will behave like a normal heading would). <div data-role="collapsible"> <h3>Collapsible block header</h3> <p>Lorem ipsum dolor sit amet etc....</p> </div> We used an h3 heading in this example, but any other heading would have looked just the same: jQuery Mobile changes completely the style of the heading to match a button's style. We can specify whether we want a collapsible block to be expanded on page load or not by adding the data-collapsed="true" attribute to the container: <div data-role="collapsible" data-collapsed="true"> <h3>This block will be collapsed (does not show content)</h3> <p>Lorem ipsum dolor sit amet etc....</p> </div> <div data-role="collapsible"> <h3>This block will expand on page load</h3> <p>This text is visible right away!</p> </div> Nested collapsible blocks Collapsible blocks can also be nested, resulting in a series of blocks which control various paragraphs and content: To create a set of nested collapsible blocks, we only need to insert a block into another block, which will be its container: <!-- Top level collapsible block --> <div data-role="collapsible"> <h3>Collapsible block header</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <!-- nested collapsible block --> <div data-role="collapsible"> <h3>Nested collapsible block</h3> <p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p> </div> </div> We may have any number of collapsible blocks nested; for example, here is another one: <!-- Top level collapsible block --> <div data-role="collapsible"> <h3>Collapsible block header</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <!-- nested collapsible block --> <div data-role="collapsible"> <h3>Nested collapsible block</h3> <p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p> <!-- nested into a nested block --> <div data-role="collapsible"> <h3>Nested into a nested collapsible block</h3> <p>Integer lectus eros, accumsan eget ultrices vel, sagittis volutpat odio.</p> </div> </div> </div>  
Read more
  • 0
  • 0
  • 2245

article-image-manifest-assurance-security-and-android-permissions-flash
Packt
29 Jun 2011
8 min read
Save for later

Manifest Assurance: Security and Android Permissions for Flash

Packt
29 Jun 2011
8 min read
Setting application permissions with the Android Manifest file When users choose to install an application on Android, they are always presented with a warning about which permissions the application will have within their particular system. From Internet access to full Geolocation, Camera, or External Storage permissions; the user is explicitly told what rights the application will have on their system. If it seems as though the application is asking for more permissions than necessary, the user will usually refuse the install and look for another application to perform the task they need. It is very important to only require the permissions your application truly needs, or else users might be suspicious of you and the applications you make available. How to do it... There are three ways in which we can modify the Android Manifest file to set application permissions for compiling our application with Adobe AIR. Using Flash Professional: Within an AIR for Android project, open the Properties panel and click the little wrench icon next to Player selection: The AIR for Android Settings dialog window will appear. You will be presented with a list of permissions to either enable or disable for your application. Check only the ones your application will need and click OK when finished. Using Flash Builder: When first setting up your AIR for Android project in Flash Builder, define everything required in the Project Location area, and click Next. You are now in the Mobile Settings area of the New Flex Mobile Project dialog. Click the Permissions tab, making sure that Google Android is the selected platform. You will be presented with a list of permissions to either enable or disable for your application. Check only the ones your application will need and continue along with your project setup: To modify any of these permissions after you've begun developing the application, simply open the AIR descriptor file and edit it as is detailed in the following sections. Using a simple text editor: Find the AIR Descriptor File in your project. It is normally named something like {MyProject}-app.xml as it resides at the project root. Browse the file for a node named <android> within this node will be another called <manifestAdditions> which holds a child node called <manifest>. This section of the document contains everything we need to set permissions for our Android application. All we need to do is either comment out or remove those particular permissions that our application does not require. For instance, this application needs Internet, External Storage, and Camera access. Every other permission node is commented out using the standard XML comment syntax of <!-- <comment here> -->: <uses-permission name="android.permission.INTERNET"/> <uses-permission name="android.permission.WRITE_EXTERNAL_ STORAGE"/> <!--<uses-permission name="android.permission.READ_PHONE_ STATE"/>--> <!--<uses-permission name="android.permission.ACCESS_FINE_ LOCATION"/>--> <!--<uses-permission name="android.permission.DISABLE_ KEYGUARD"/>--> <!--<uses-permission name="android.permission.WAKE_LOCK"/>-- > <uses-permission name="android.permission.CAMERA"/> <!--<uses-permission name="android.permission.RECORD_ AUDIO"/>--> <!--<uses-permission name="android.permission.ACCESS_ NETWORK_STATE"/>--> <!--<uses-permission name="android.permission.ACCESS_WIFI_ STATE"/>--> How it works... The permissions you define within the AIR descriptor file will be used to create an Android Manifest file to be packaged within the .apk produced by the tool used to compile the project. These permissions restrict and enable the application, once installed on a user's device, and also alert the user as to which activities and resources the application will be given access to prior to installation. It is very important to provide only the permissions necessary for an application to perform the expected tasks once installed upon a device. The following is a list of the possible permissions for the Android manifest document: ACCESS_COARSE_LOCATION: Allows the Geoloctaion class to access WIFI and triangulated cell tower location data. ACCESS_FINE_LOCATION: Allows the Geolocation class to make use of the device GPS sensor. ACCESS_NETWORK_STATE: Allows an application to access the network state through the NetworkInfo class. ACCESS_WIFI_STATE: Allows and application to access the WIFI state through the NetworkInfo class. CAMERA: Allows an application to access the device camera. INTERNET: Allows the application to access the Internet and perform data transfer requests. READ_PHONE_STATE: Allows the application to mute audio when a phone call is in effect. RECORD_AUDIO: Allows microphone access to the application to record or monitor audio data. WAKE_LOCK: Allows the application to prevent the device from going to sleep using the SystemIdleMode class. (Must be used alongside DISABLE_KEYGUARD.) DISABLE_KEYGUARD: Allows the application to prevent the device from going to sleep using the SystemIdleMode class. (Must be used alongside WAKE_LOCK.) WRITE_EXTERNAL_STORAGE: Allows the application to write to external memory. This memory is normally stored as a device SD card. Preventing the device screen from dimming The Android operating system will dim, and eventually turn off the device screen after a certain amount of time has passed. It does this to preserve battery life, as the display is the primary power drain on a device. For most applications, if a user is interacting with the interface, that interaction will prevent the screen from dimming. However, if your application does not involve user interaction for lengthy periods of time, yet the user is looking at or reading something upon the display, it would make sense to prevent the screen from dimming. How to do it... There are two settings in the AIR descriptor file that can be changed to ensure the screen does not dim. We will also modify properties of our application to complete this recipe: Find the AIR descriptor file in your project. It is normally named something like {MyProject}-app.xml as it resides at the project root. Browse the file for a node named <android> within this node will be another called <manifestAdditions>, which holds a child node called <manifest>. This section of the document contains everything we need to set permissions for our Android application. All we need to do is make sure the following two nodes are present within this section of the descriptor file. Note that enabling both of these permissions is required to allow application control over the system through the SystemIdleMode class. Uncomment them if necessary. <uses-permission android_name="android.permission.WAKE_LOCK" /> <uses-permission android_name="android.permission.DISABLE_ KEYGUARD" /> Within our application, we will import the following classes: import flash.desktop.NativeApplication; import flash.desktop.SystemIdleMode; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.text.TextField; import flash.text.TextFormat; Declare a TextField and TextFormat pair to trace out messages to the user: private var traceField:TextField; private var traceFormat:TextFormat; Now, we will set the system idle mode for our application by assigning the SystemIdleMode.KEEP_AWAKE constant to the NativeApplication.nativeApplication.systemIdleMode property: protected function setIdleMode():void { NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE; } We will, at this point, continue to set up our TextField, apply a TextFormat, and add it to the DisplayList. Here, we create a method to perform all of these actions for us: protected function setupTraceField():void { traceFormat = new TextFormat(); traceFormat.bold = true; traceFormat.font = "_sans"; traceFormat.size = 24; traceFormat.align = "left"; traceFormat.color = 0xCCCCCC; traceField = new TextField(); traceField.defaultTextFormat = traceFormat; traceField.selectable = false; traceField.multiline = true; traceField.wordWrap = true; traceField.mouseEnabled = false; traceField.x = 20; traceField.y = 20 traceField.width = stage.stageWidth-40; traceField.height = stage.stageHeight - traceField.y; addChild(traceField); } Here, we simply output the currently assigned system idle mode String to our TextField, letting the user know that the device will not be going to sleep: protected function checkIdleMode():void { traceField.text = "System Idle Mode: " + NativeApplication. nativeApplication.systemIdleMode; } When the application is run on a device, the System Idle Mode will be set and the results traced out to our display. The user can leave the device unattended for as long as necessary and the screen will not dim or lock. In the following example, this application was allowed to run for five minutes without user intervention: How it works... There are two things that must be done in order to get this to work correctly and both are absolutely necessary. First, we have to be sure the application has correct permissions through the Android Manifest file. Allowing the application permissions for WAKE_LOCK and DISABLE_KEYGUARD within the AIR descriptor file will do this for us. The second part involves setting the NativeApplication.systemIdleMode property to keepAwake. This is best accomplished through use of the SystemIdleMode.KEEP_AWAKE constant. Ensuring that these conditions are met will enable the application to keep the device display lit and prevent Android from locking the device after it has been idle.
Read more
  • 0
  • 0
  • 2449
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €14.99/month. Cancel anytime
article-image-iphone-issues-related-calls-sms-and-contacts
Packt
28 Jun 2011
9 min read
Save for later

iPhone: Issues Related to Calls, SMS, and Contacts

Packt
28 Jun 2011
9 min read
  iPhone JavaScript Cookbook Clear and practical recipes for building web applications using JavaScript and AJAX without having to learn Objective-C or Cocoa         Read more about this book       (For more resources related to this subject, see here.) At the time of publication, working with contacts requires us to develop native applications. But we can use JavaScript with the PhoneGap framework for building these kinds of applications for the iPhone. This is the main reason for applying this framework for the recipes included in this article. This article focuses on issues related to calls, SMS, and contacts. We'll learn how to handle contacts and how to send an SMS or place a phone call simply by interacting with the user interface. Calling a number In this recipe, you'll learn how to call a number when a user clicks on a button in the user interface. Specifically, we're going to build a simple list containing our contacts where each represents a person and their phone number. After clicking on one of these elements the dial screen will be opened and the user will only need to click on the green button for calling the specified number. We only need to build a simple XHTML file for this recipe. It can be found at code/ch08/call.html in the code bundle provided on the Packtpub site. Code files can be downloaded at the Packt website. Getting ready This recipe requires the use of the iWebKit framework. How to do it... Open your favorite text editor or IDE and create a new file called call.html. Add the standard XHTML headers and the required lines for invoking the JavaScript and CSS files provided by iWebKit: <link href="../iwebkit/css/style.css" rel="stylesheet media="screen" type="text/css" /> <script src="../iwebkit/javascript/functions.js" type="text/javascript"></script> Add the main HTML code for defining our user interface: <body class="list"> <div id="topbar"> <div id="title">Call</div> </div> <div id="content"> <ul> <li class="title">Contacts</li> <li><a class="noeffect" href="tel:555-666-777"> <span class="name">Aaron Stone</span></a></li> <li><a class="noeffect" href="tel:555-888-999"> <span class="name">Ben Jackson</span></a></li> <li><a class="noeffect" href="tel:555-222-333"> <span class="name">Bob McKenzie</span></a></li> <li><a class="noeffect" href="tel:555-444-666"> <span class="name">Luke Johnson</span></a></li> <li><a class="noeffect" href="tel:555-333-666"> <span class="name">Michael Sterling</span></a></li> </ul> </div> Now, save your new file and load it on your device. The following screenshot shows you the result of loading the file built for this recipe: How it works... The most important part of the code in this recipe is the anchor element inside each <li> tag. The href attribute of the anchor element is using a string, which represents a specific protocol followed by a number. In fact, tel identifies the protocol and the iPhone, understanding its meaning displays the dial screen allowing the user to call a number. On the other hand, the class noeffect was applied to each anchor for opening the dial screen in fullscreen mode. From a strict point of view, iWebkit is not a must for calling numbers. Safari Mobile indentifies the tel protocol by default. However, we used the mentioned framework because it helps us to easily construct a list with many items. What happens if you are using an iOS device other than the iPhone? It is not possible to call numbers from an iPad or iPod touch as of now. The code developed for this recipe works differently in these devices. Instead of calling numbers, iPad and iPod touch will ask you if you want to save numbers in the address book. Sending an SMS to a number The previous recipe explained how you can call a number from your applications. This recipe will show you how to send an SMS to a selected number. For simplicity we're going to use the same approach. We'll develop a simple XHTML file displaying a list with different contacts. When the user clicks on one of the contacts the iPhone will display the screen for sending an SMS. Getting ready As in the previous recipe we will use the iWebKit framework. As both recipes are similar, we're going to use the same XHTML file developed for the previous recipe. How to do it... Open the call.html file and replace the content of the href attribute of each <li>item for a new string starting with sms: instead of tel. For example, the first item will be the following: <li> <a class="noeffect" href="sms:555-666-777"> <span class="name">Aaron Stone</span> </a> </li> Save the new content of the original file as a new file called sms.html, then you'll be ready for testing it on your iPhone. How it works... As you've learned in the previous recipe, Safari Mobile identifies the tel protocol for calling numbers. In the same way, sms is used for sending SMS's. Also for this recipe the iWebKit is used for building the user interface. Selecting contacts Thanks to this recipe we'll learn how to select a contact from the address book of the iPhone and to display its related information. Our goal is quite simple; when the user clicks on a button, a new screen will display all available contacts. After clicking on one of these elements, the complete name of the selected contact will be displayed in the main screen. Although this recipe is very simple, you can apply it for building complex applications that require dealing with contacts available through the address book of the iPhone. The complete code for this recipe can be reached at code/ch08/queryAddress in the code bundle provided on the Packtpub site. Getting ready For this recipe we'll use three different frameworks: PhoneGap, XUI, and UiUIKit. Before continuing, make sure you have these frameworks installed on your machine. Also, remember you'll need a Mac OS X computer with the iOS SDK and Xcode installed. How to do it... The first step is to create a new PhoneGap project through Xcode. After creating your new project, the next step will be to open the main index.html file for adding our own code for this recipe. First, you should add the following lines inside the head section of the mentioned HTML file: <script type="text/javascript" src="xui-2.0.0..min.js"></script> <link rel="stylesheet" href="uiuikit/stylesheets/iphone.css" /> <style type="text/css"> #mybtn { margin-right: 12px; } </style> The next step is to comment out the JavaScript function preventBehavior() and the line below this function. Then, we're going to add our JavaScript code: function searchContact() { navigator.contacts.chooseContact(onSucessContact); } function onSucessContact(contact) { var selectedContact = contact.name; x$('#ul_contacts').html( 'inner', "<li>" + selectedContact + "</li>"); } Finally, we'll modify the original body section adding the following lines of HTML code: <div id="header"> <h1>Contacts</h1> </div> <h1>Working with contacts</h1> <p id="p_btn"> <a href="#" id="mybtn" onclick="searchContact()" class="button white">Select</a> </p> <ul id='ul_contacts'></ul> Before continuing and after applying all changes inside the code, we need to copy some files to the www directory of our project. Specifically, we're going to copy the uiuikit directory and the xui-2.0.0.min.js file. Remember, these components belong to the UiUIKit and XUI framework respectively. Save your project and click on the Build and Run button of Xcode for testing your new application. After loading the application in the iPhone Simulator, you can see a screen similar to next screenshot: When the user clicks on the button Select, a list with all the available contacts will be displayed as shown in the following screenshot: After selecting one of the items showed in the list, our application will display the data for the selected contact: How it works... PhoneGap provides a JavaScript function for accessing the predefined screen of the iPhone for selecting contacts. The name of this function is ChooseContact() and it is invoked through the navigator.contacts predefined object. It encapsulates the access to the address book of the iPhone. As a parameter, this function requires a callback method that will be invoked when a contact is selected. In our case, we implemented a function called onSuccessContact(), which captures the complete name of the contact displaying the result in a simple list. onSuccesContact uses a parameter called contact, which represents an object containing the information related to the selected contact from the address book. The XUI framework allows us to add new items to our ul list by manipulating the DOM of the HTML page. On the other hand, the UiUIKit framework was used for building the user interface for our small application. We used a bit of CSS for centering our button. Actually, we modified the right margin of this widget. The CSS style for this appears before the JavaScript code, also inside the head section.
Read more
  • 0
  • 0
  • 1661

article-image-top-5-must-have-android-applications
Packt
28 Jun 2011
6 min read
Save for later

Top 5 Must-have Android Applications

Packt
28 Jun 2011
6 min read
  Android Application Testing Guide Build intensively tested and bug free Android applications     1. ES File Explorer Description: ES File Explorer has everything you would expect from a file explorer – you can copy, paste, rename and delete files. You can select multiple files at a time just as you would on your PC or MAC. You can also compress files to zip or gz. One of the best features of ES file explorer is the ability to connect to network shares – this means you can connect to a shared folder on your LAN and transfer files to and from your Android device. Its user interface is very simple, quick and easy to use. Screenshots:   Features: Multiselect and Operate files (Copy, Paste, Cut/Move, Create, Delete and Rename, Share/Send) in the phone and computers Application manager -- Manage apps(Install, Uninstall, Backup, Shortcuts, Category) View Different file formats, photos, docs, videos anywhere, support third party applications such as Document To Go to open document files Text viewers and editors Bluetooth file transfer tool Access your Home PC, via WIFI with SMB Compress and Decompress ZIP files, Unpack RAR files, Create encrypted (AES 256 bit) ZIP files Manage the files on the FTP server as the ones on the sd card Link: This application is available for download at: https://market.android.com/details?id=com.estrongs.android.pop 2. Go Sms Pro Description: GO SMS Pro is the ultimate messaging application for Android devices. There is a nice setting that launches a pop-up for incoming messages. Users can then respond or delete directly within the window. The app supports batch actions for deleting, marking all, or backing up. It is highly customizable; everything from the text color, to the color of the background, SMS ringtones for specific contacts, and themes for the SMS application can be customized. Another interesting feature that you can take advantage of is the multiple plug-ins that are available as free download in the market. The Facebook chat plug-in makes it possible to receive and send Facebook chat messages and since these messages are sent through the Facebook network it does not affect your SMS messages at all. Screenshots: Features: GO-MMS service (FREE), you may send picture/music to your friend(ever they are no GO SMS) through one SMS with 2G/3G/4G or WIFI Many cool themes; also support DIY theme, and Wallpaper Maker plug-in; Fully customizable look; Supports chat style and list style; Font changeable SMS backup and restore by all or by conversations, supports XML format, send backup file by email Support schedule SMS; Group texting Settings backup and restore Notification with privacy mode and reminder notification Security lock, support lock by thread; Blacklist Link: This application is available for download at: https://market.android.com/details?id=com.jb.gosms 3. Dolphin HD browser Description: Dolphin Browser HD is a professional mobile browser presented by Mobotap Inc. Dolphin Browser HD is the most advanced and customizable web browser. You can browse the Web with the greatest speed and efficiency by using Dolphin browser HD. The main browsing screen is clean and uncluttered. Other than the Home and Refresh buttons that flank the address bar, Dolphin HD doesn't clutter the main interface with other quick-access buttons. In addition to tabbed browsing, bookmarking (that syncs to Google bookmarks), and multitouch zooming, it can also flag sites to read later as well as a tie-in to Delicious. You can search content within a page, subscribe to RSS feeds through Google Reader, and share links with social networks. Another great feature of this app is the capability to download YouTube videos. Screenshots: Features: Manage Bookmarks Multi Touch pinch zoom Unlimited Tabs Colorful theme pack Gestures as shortcuts for common commands You can save web pages to read them offline with all images preserved Link: This application is available for download at: https://market.android.com/details?id=mobi.mgeek.TunnyBrowser 4. Winamp Description: The one big advantage that Winamp has over other playback apps is that it can sync tracks wirelessly to the device over your home network, so you don’t have to fuss with a USB cable, making it easier to manage your music. You can set Winamp to sync automatically, every time you connect your Android phone to Winamp, which makes it incredibly easy to send new playlists, purchases and downloads to your portable player, sans USB. The interface is probably the most notable upgrade over the stock player. The playback controls remain on-screen pretty much wherever you are in the app – a small touch, but one that vastly improves the functionality of Winamp. Being able to control playback from any point is more useful than you might expect. Screenshots: Features: iTunes library & playlist import Wireless & wired sync with the desktop Winamp Media Player Over 45k+ SHOUTcast Internet radio stations Integrated Android Search & “Listen to” voice actions Play queue management Playlists and playlist shortcuts Extras Menu – Now Playing data interacts with other installed apps Link: This application is available for download at: https://market.android.com/details?id=com.nullsoft.winamp 5. Advanced Task Killer Description: One click to kill applications running in the background. Advanced Task Killer is pretty simple and easy to use. It allows you to see what applications are currently running and offers the ability to terminate them quickly and easily, thus freeing up valuable memory for other processes. It also remembers your selections, so the next time you launch it, the previously spared apps remain unchecked and the previously selected ones are checked and are ready to be shut down. You can choose to have Advanced Task Killer start at launch and there’s even the option to have it appear in your notifications bar for swift access. Screenshots: Features: Kill multiple apps with one tap Adjust the security levels It comes with a notification bar icon You can kill apps automatically by selecting one of auto-kill level: Safe, Aggressive or Crazy Link: This application is available for download at: https://market.android.com/details?id=com.rechild.advancedtaskkiller Summary In this article we discussed the Top 5 must-have applications for your android phone. Further resources on this subject: Android Application Testing: Getting Started [Article] Flash Development for Android: Audio Input via Microphone [Article] Android Application Testing: TDD and the Temperature Converter [Article] Android User Interface Development: Animating Widgets and Layouts [Article]
Read more
  • 0
  • 2
  • 3469

article-image-iphone-javascript-installing-frameworks
Packt
23 Jun 2011
14 min read
Save for later

iPhone JavaScript: Installing Frameworks

Packt
23 Jun 2011
14 min read
  iPhone JavaScript Cookbook Clear and practical recipes for building web applications using JavaScript and AJAX without having to learn Objective-C or Cocoa         Read more about this book       (For more resources related to this subject, see here.) Introduction Many web applications implement common features independent of the final purpose for which they have been designed. Functionalities and features such as authentication, forms validation, retrieving records from a database, caching, logging, and pagination are very common in modern web applications. As a developer, surely you have implemented one or more of these features in your applications more than once. Good developers and software engineers insist on concepts, such as modularity, reusability, and encapsulation; as a consequence you can find a lot of books, papers, and articles talking about how to design your software using these techniques. In fact, modern and popular methodologies, such as Extreme Programming, Scrum, and Test-driven Development are based on those principles. Although this approach sounds very appealing in theory, it might be complicated to carry it out in practice. Developing any kind of software from scratch for running in any platform is undoubtedly a hard task. Complexity grows up when the target platform, operating system, or machine has its own specific rules and mechanisms. Some tools can make our job less complicated but only one kind of them is definitely a safe bet. It is here when we meet frameworks, a set of proven code that offers common functionality and standard structures for software development. This code makes our life much easier without reinventing the wheel and gives a skeleton to our applications, making sure that we're doing things correctly. In addition, frameworks avoid starting from scratch once more. From a technical point of view, most frameworks are a set of libraries implementing functions, classes, and methods. Using frameworks, we can save time and money, writing less code due to its code skeleton, and features implemented on it. Usually, frameworks force us to follow standards and they offer well-proven code avoiding common mistakes for beginners. Tasks such as testing, maintenance, and deployment are easier to do using frameworks due to the tools and mechanisms included. On the other hand, the learning curve could be a big and difficult drawback for beginners. Through this article, we'll learn how to install the main frameworks for JavaScript, HTML, and CSS development for iPhone. All of them offer a base to develop applications with a consistent and native look and feel using different methods. While some of them are focused on the user interface, others allow using AJAX in an efficient and easy way. Even some frameworks allow building native applications from the original code of the web application. We have the chance to choose which is better to fulfill our requirements; it is even possible to use more than one of these solutions for the same application. For our recipes, we'll use the following frameworks: iUI: This is focused on the look and feel of iPhone and consists of CSS files, images, and a small JavaScript library. Its objective is to get a web application running on the device with a consistent interface such as a native application. This framework establishes a correspondence between HTML tags and conventions used for developing native applications. UiUIKit: Using a set of CSS and image files, it provides a coherent system for building web applications with a graphic interface such as native iPhone applications. The features offered for this framework are very similar to iUI. XUI: This is a pure JavaScript library specific for mobile development. It has been designed to be faster and lighter than other similar libraries, such as jQuery, MooTools, and prototype. iWebKit: This is developed specifically for Apple's devices and is compatible with CSS3 standard; it helps to write web applications or websites with minimum HTML knowledge. Its modular design supports plugins for adding new features and we can build and use the themes for UI customization. WebApp.Net: This framework comes loaded with JavaScript, CSS, and image files for developing web application for mobile devices that uses WebKit engine in its web browsers. Besides building interfaces, this framework includes functionality to use AJAX in an easy and efficient way. PhoneGap: This is designed to minimize efforts for developing native mobile applications for different operating systems, platforms, and devices. It is based on the WORE (Write once, run anywhere) principle and it allows conversion from a web application into a native application. It supports many platforms and operating systems, such as iOS, Android, webOS, Symbian, and BlackBerry OS. Apple Dashcode: Formally, this is a software development tool for Mac OS X included in Leopard and Snow Leopard versions, and focused on widget development for these operating systems. However, the last versions allow you to write web applications for iPhone and other iOS devices offering a graphic interface builder. Installing the iUI framework This recipe shows how to download and install the iUI framework on different operating systems. Particularly, we'll cover Microsoft Windows, Mac OS X, and GNU/Linux. Getting ready The first step is to install and get ready; some tools need to be downloaded and decompressed. As computer users, we know how to decompress files using software such as WinZip, Ark, or the built-in utility on Mac OS X. You will surely have installed a web browser on your computer. If you are a Linux or Mac developer, you already know how to use curl or wget. These tools are very useful for quick download and you only need to use the command line through applications such as GNOME Terminal, Konsole, iTerm, or Terminal. iUI is an open source project, so you can download the code for free. The open source project releases some stable versions packed and ready to download, but it is also possible to download a development version. This one could be suitable if you prefer working with the latest changes made by the official developers contributing to the project. Due to this, developers are using Mercurial version control and thus we'll need to install a client for it to get access to this code. How to do it... iUI is an open source project so you can download the code for free. Open your favorite web browser and enter this URL: http://code.google.com/p/iui/downloads/list In that web page, you'll see a list with files that refer to different release versions of this framework. Clicking on the link corresponding to the latest release's drives takes you to a new web page that shows you a new link for the file. Click on it for instant downloading. (Move the mouse over the image to enlarge it.) If you are a GNU/Linux user or a Mac developer you will be used to command line. Open your terminal application and launch this command from your desired directory: $ wget http://iui.googlecode.com/files/iui-0.31.tar.gz Once you have downloaded the tarball file, it's time to extract its content to a specific folder on our computer. WinZip and WinRAR are the most popular tools to do this task on Windows. Linux distributions, by default, install similar tools such as File Roller and Ark. Double-clicking from the download window of the Safari browser will extract the files directly to your default folder on your Mac, which is usually called Downloads. For command-line enthusiasts, execute the following command: $ tar -zxvf iui-0.31.tar.gz How it works... After decompressing the downloaded file, you'll find a folder with different subfolders and files. The most important is a subfolder called iui that contains CSS, images, and JavaScript files for building our web applications for iPhone. We need to copy this subfolder to our working folder where other application files reside. Sharing this framework across different web applications is possible; you only need to put the iUI at a place where these applications have permissions to access. Usually, this place is a folder under the DocumentRoot of your web server. If you're planning to write a high load application, it would be a good idea to use a cloud or CDN (Content Delivery Network) service such as Amazon Simple Storage Services (Amazon S3) for hosting and serving static HTML, CSS, JavaScript, and image files. Installing the iUI framework is a straightforward process. You simply download and decompress one file, and then copy one folder into an other, which has permission to be accessed by the web server. Apache is one of the most used and extended web servers in the world. Other popular options are Internet Information Server (IIS), lighttpd, and nginx. Apache web server is installed by default on Mac OS X; most of the operating systems based on Linux and UNIX offer binary packages for easy installation and you can find binary files for installing on Windows as well. IIS was designed for Windows operating systems, meanwhile, lighttpd and nginx are winning popularity and are used on UNIX systems as Linux's distros, FreeBSD, and OpenBSD. Ubuntu Linux uses /var/www/ directory as the main DocumentRoot for Apache. So, in order to share iUI framework across applications, you can copy the folder to the other folder by executing this command: $ cp -r iui-0.31/ui /var/www/iui If you are a Mac user, your target directory will be /Library/WebServer/Documents/iui. There's more... Inside the samples subfolder, you'll find some files showing capabilities of this framework, including HTML and PHP files. Some examples need a web server with PHP support but you can test others using Safari web browser or an other WebKit's browser such as Safari or Google Chrome. Open index.html with a web browser and use it as your starting point. If you prefer to use the latest version in development from the version control, you'll need to install a Mercurial client. Most of the GNU/Linux distribution such as Fedora, Debian, and Ubuntu includes binary packages ready to install them. Usually, the name of the binary package is mercurial. The following command will install the client on Ubuntu Linux: $ sudo apt-get install mercurial Mercurial is an open source project and offers a binary file ready to install for Mac OS X and Windows systems. If you're using one of these, go to the following page and download the specific file for your operating system and version: http://mercurial.selenic.com/downloads/ After downloading, you can install the client using the regular process for your operating system. Mac users will find a ZIP file containing a binary package. For Windows, the distributed file is a MSI (Microsoft Installer), ready for self-installation after clicking on it. Despite that the client of this version control was developed for the command line, we can find some GUI tools online such as TortoiseHG for Windows. These tools are intuitive and user-friendly, allowing an interactive use between the user and the source files hosted in the version control system. TortoiseHG can be downloaded from the same web page as the Mercurial client. Finally, we'll download the version development of the iUI framework executing the following command: $ hg clone https://iui.googlecode.com/hg/ iui The new iui folder includes all files of the iUI framework. We should copy this folder to our DocumentRoot. If you want to know more about this framework, point your browser at the official wiki project: http://code.google.com/p/iui/w/list Also, taking a look at the complete code of the project may be interesting for advanced developers or just for people wanting to learn more about internal details: http://code.google.com/p/iui/source/browse Installing the UiUIKit framework UiUIKit is the short name of the Universal iPhone UI Kit framework. The development of this framework is carried out through an open source project hosted in Google Code and is distributed under the GNU Public License v3. Let's see how to install it on different operating systems. Getting ready As the main project file is distributed as a ZIP file, we'll need to use one tool for decompressing these kind of files. Most of the modern operating systems include tools for this process. As seen in the previous recipe, we can use wget or curl programs for downloading the files. If you are planning to read the source code or you'd like to use the current development version of the framework, you'll need a Subversion client as the UiUIKit project is working with this open source version control. How to do it... Open your web browser and type the following URL: http://code.google.com/p/iphone-universal/downloads/list After downloading, click on the link for the latest version from the main list, for instance, the link called UiUIKit-2.1.zip. The next page will show you a different link for this file that represents the version 2.1 of the UiUIKit framework. Click on the link and the file will start downloading immediately. Mac users will see how the Safari browser shows a window with the content of the compressed file, which is a folder called UiUIKit, which is stored in the default folder for downloads. Command line's fans can use these simple commands from their favorite terminal tool: $ cd ~$ curl -O http://iphone-universal.googlecode.com/files/UiUIKit-2.1.zip After downloading, don't forget to decompress the file on your web-specific directory. The commands given next execute this action on Linux and Mac OS X systems: $ cd /var/www/$ unzip ~/UiUIKit-2.1.zip How it works... The main folder of the UiUIKit framework contains two subfolders called images and stylesheets. The first one includes many images used to get a native look for web applications on the iPhone. The other one offers a CSS file called iphone.css. We only need the images subfolder with its graphic files and the CSS file. In order to use this framework in our projects, we need to allow our HTML files access to the images and the CSS file of the framework. These files should be in a folder with permissions for the web server. For example, we'll have a directory structure for our new web application for iPhone as follows: myapp/ index.html images/ actionButtons.png apple-touch-icon.png backButton.png toolButton.png whiteButton.png first.html second.html stylesheets/ iphone.css Remember that this framework doesn't include HTML files; we only need a bunch of the graphic files and one stylesheet file. The HTML files showed in the previous example will be our own files created for the web application. We'll also find a lot of examples on different HTML files located in the root directory, outside the mentioned subfolders. These files are not required for development but they can be very useful to show how to use some features and functionalities. There's more... For an initial contact with the capabilities of the framework it would be interesting to take a look at the examples included in the main directory of the framework. We can load the index.html in our browser. This file is an index to the different examples and offers a native interface for the iPhone. Safari could be used but is better to access from a real iPhone device. Subversion is a well-proven version control used by many developers, companies, and, of course, open source projects. UiUIKit is an example of these projects using this popular version control. So, to access the latest version in development, we'll need a client to download it. Popular Linux distributions, including Ubuntu and Debian have binary packages ready to install. For instance, the following command is enough to install it on Ubuntu Linux: $ sudo apt-get install subversion The last versions of Mac OS X, including Leopard and Snow Leopard, includes a Subversion client ready to use. For Windows, you can download Slik SVN available for 32-bit and 64-bits platforms; installation programs can be downloaded from: http://www.sliksvn.com/en/download. When you are sure that your client is running, you could execute it for getting the latest development version of the UiUIKit framework. Mac and Linux users will execute the following command: $ svn checkout http://iphone-universal.googlecode.com/svn/trunk/ UiUIKit All information related to the UiUIKit framework project could be found at: http://code.google.com/p/iphone-universal/
Read more
  • 0
  • 0
  • 4663

article-image-jquery-mobile-organizing-information-list-views
Packt
23 Jun 2011
8 min read
Save for later

jQuery Mobile: Organizing Information with List Views

Packt
23 Jun 2011
8 min read
jQuery Mobile First Look Discover the endless possibilities offered by jQuery Mobile for rapid Mobile Web Development You might have noticed that the vast majority of websites built using jQuery Mobile have their content laid out in very similar ways; sure, they differ in the design, colors, and overall feel, but they all have a list-based layout. There is a way in which we can organize our information and take advantage of each and every space in the browser: information is displayed vertically, one piece under another. There are no sidebars of any kind and links are organized in lists – for a cleaner and tidy look. But list views are also used to actually be a list of information. Some examples may be lists of albums, names, tasks, and so on: after all, our purpose is to build a mobile web application and the majority of services and pages can be organized in a way which closely resembles a list. Basics and conventions for list views Due to the particular nature of lists, list views are coded exactly the same way a standard HTML unordered list would. After all, the purpose of list views is to organize our information in a tidy way, presenting a series of links which are placed one under another; the easiest way to grasp their usefulness is, in my opinion, imagining a music player application. A music player would need a clean enough interface, listing the artists, albums, and songs by name. In order to play a song, the user would need to select an artist, and then choose the album in which the song he wishes to play has been released. To create our first view (artists), we would use the following code. Make sure you add the data-role="listview" attribute to the unordered list tag: <ul data-role="listview"> <li><a href="astra.html">Astra</a></li> <li><a href="zappa.html">Frank Zappa</a></li> <li><a href="tull.html">Jethro Tull</a></li> <li><a href="radiohead.html">Radiohead</a></li> <li><a href="who.html">The Who</a></li> </ul> The jQuery Mobile framework automatically styles the list elements accordingly, and adds a right arrow icon. List elements fill the full width of the browser window: Whenever an item is selected (click/tap event), jQuery Mobile will parse the code inside the list element and issue an AJAX request for the first URL found. The page (obtained via AJAX) is then inserted into the existing DOM and a page transition event is triggered. The default page transition is a slide-left animation; clicking the back button on the newly displayed page will result in a slide-right animation. Choosing the list type as per your requirements A somewhat large variety of lists are available for us to choose from in order to make use of the type of list view that is best suited to our needs. Below are listed (sorry, no pun intended!) the different types of list views along with a brief description of how to use them and what part of code we need to change in order to obtain a certain list view. Nested lists Bearing in mind that list views elements are based on the standard HTML unordered list element, we might be wondering what would happen if we try and create a second list inside a list view. By nesting a ul element inside list items, jQuery Mobile will adopt a different kind of behavior to our list items. Our first step toward the creation of a nested list is removing any link present in the list item, as a click event will show the nested list instead of redirecting to another page. The child list will be put into a new "page" with the title of the parent in the header. We're now implementing nested list elements into our sample music player interface by changing our markup to the following. This way, we are able to browse artists and albums. Please note that we have removed any links to external pages: <ul data-role="listview"> <li>Astra <ul> <li><a href="astra_weirding.html">The Weirding</a></li> </ul> </li> <li>Frank Zappa <ul> <li><a href="zappa_hotrats.html">Hot Rats</a></li> <li><a href="zappa_yellowshark.html">Yellow Shark</a></li> </ul> </li> <li>Jethro Tull <ul> <li><a href="tull_aqualung.html">Aqualung</a></li> <li><a href="tull_thick.html">Thick as a Brick</a></li> </ul> </li> <li>Radiohead <ul> <li><a href="radiohead_ok.html">OK Computer</a></li> <li><a href="radiohead_rainbows.html">In Rainbows</a></li> <li><a href="radiohead_kol.html">The King of Limbs</a></li> </ul> </li> <li>The Who <ul> <li><a href="who_next.html">Who's Next</a></li> <li><a href="who_q.html">Quadrophenia</a></li> <li><a href="who_tommy.html">Tommy</a></li> </ul> </li> </ul> If we clicked on the Radiohead element, we would then be able to see the following page: By default, child list will be given a Swatch B theme to indicate they are at a secondary level of navigation; we can select a different color swatch by specifying a data-theme attribute on the child list element. We can see the header turned blue, and the artist name is used as the header. We have a choice to go back to the previous page (artists) or click again onto a list item (album) to view more. Numbered lists Our music player interface has reached the point in which we need to list the tracks contained in an album. Of course, tracks have a sequence, and we want to give the user the possibility to see what track number is without having to count them all – and without writing numbers manually, that would be terrible! In a very similar fashion, we can use ordered list elements (ol) to obtain numbering: jQuery Mobile will try to use CSS to display numbers or, if not supported, JavaScript. The following code lists all of the tracks for an album: Note there is no limit to the number of lists you can nest. <ul> <!-- ... --> <li>Radiohead <ul> <li><a href="radiohead_ok.html">OK Computer</a></li> <li><a href="radiohead_rainbows.html">In Rainbows</a></li> <li>The King of Limbs <ol> <li><a href="play.html">Bloom</a></li> <li><a href="play.html">Morning Mr. Magpie</a></li> <li><a href="play.html">Little by Little</a></li> <li><a href="play.html">Feral</a></li> <li><a href="play.html">Lotus Flower</a></li> <li><a href="play.html">Codex</a></li> <li><a href="play.html">Give Up the Ghost</a></li> <li><a href="play.html">Separator</a></li> </ol> </li> </ul> </li> <!-- ... --> </ul>
Read more
  • 0
  • 0
  • 4043
article-image-flash-development-android-audio-input-microphone
Packt
22 Jun 2011
4 min read
Save for later

Flash Development for Android: Audio Input via Microphone

Packt
22 Jun 2011
4 min read
  Flash Development for Android Cookbook Introduction Camera and microphone are standard accessories on most mobile devices and Android devices are no exception to this. In the previous article we dealt with Visual Input via Camera. The present article will cover encoding raw audio captured from the device microphone and encoding it to WAV or MP3 for use on other platforms and systems. All of the recipes in this article are represented as pure ActionScript 3 classes and are not dependent upon external libraries or the Flex framework. Therefore, we will be able to use these examples in any IDE we wish. The reader is advised to refer to the first recipe of Flash Development for Android: Visual Input via Camera for detecting microphone support. Using the device microphone to monitor audio sample data By monitoring the sample data being returned from the Android device microphone through the ActionScript Microphone API, we can gather much information about the sound being captured, and perform responses within our application. Such input can be used in utility applications, learning modules, and even games. How to do it... We will set up an event listener to respond to sample data reported through the Microphone API: First, import the following classes into your project: import flash.display.Sprite; import flash.display.Stage; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.SampleDataEvent; import flash.media.Microphone; import flash.text.TextField; import flash.text.TextFormat; Declare a TextField and TextFormat object pair to allow visible output upon the device. A Microphone object must also be declared for this example: private var mic:Microphone; private var traceField:TextField; private var traceFormat:TextFormat; We will now set up our TextField, apply a TextFormat, and add the TextField to the DisplayList. Here, we create a method to perform all of these actions for us: protected function setupTextField():void { traceFormat = new TextFormat(); traceFormat.bold = true; traceFormat.font = "_sans"; traceFormat.size = 44; traceFormat.align = "center"; traceFormat.color = 0x333333; traceField = new TextField(); traceField.defaultTextFormat = traceFormat; traceField.selectable = false; traceField.mouseEnabled = false; traceField.width = stage.stageWidth; traceField.height = stage.stageHeight; addChild(traceField); } Now, we must instantiate our Microphone object and set it up according to our needs and preferences with adjustments to codec, rate, silenceLevel, and so forth. Here we use setSilenceLevel() to determine what the minimum input level our application should consider to be "sound" and the rate property is set to 44, indicating that we will capture audio data at a rate of 44kHz. Setting the setLoopBack () property to false will keep the captured audio from being routed through the device speaker: protected function setupMic():void { mic = Microphone.getMicrophone(); mic.setSilenceLevel(0); mic.rate = 44; mic.setLoopBack(false); } Once we have instantiated our Microphone object, we can then register a variety of event listeners. In this example, we'll be monitoring audio sample data from the device microphone, so we will need to register our listener for the SampleDataEvent.SAMPLE_DATA constant: protected function registerListeners():void { mic.addEventListener(SampleDataEvent.SAMPLE_DATA, onMicData); } As the Microphone API generates sample data from the Android device input, we can now respond to this in a number of ways, as we have access to information about the Microphone object itself, and more importantly, we have access to the sample bytes with which we can perform a number of advanced operations: public function onMicData(e:SampleDataEvent):void { traceField.text = ""; traceField.appendText("activityLevel: " + e.target.activityLevel + "n"); traceField.appendText("codec: " + e.target.codec + "n"); traceField.appendText("gain: " + e.target.gain + "n"); traceField.appendText("bytesAvailable: " + e.data.bytesAvailable + "n"); traceField.appendText("length: " + e.data.length + "n"); traceField.appendText("position: " + e.data.position + "n"); } The output will look something like this. The first three values are taken from the Microphone itself, the second three from Microphone sample data: How it works... When we instantiate a Microphone object and register a SampleDataEvent.SAMPLE_DATA event listener, we can easily monitor various properties of our Android device microphone and the associated sample data being gathered. We can then respond to that data in many ways. One example would be to move objects across the Stage based upon the Microphone.activityLevel property. Another example would be to write the sample data to a ByteArray for later analysis. What do all these properties mean? activityLevel: This is a measurement indicating the amount of sound being received codec: This indicates the codec being used: Nellymoser or Speex gain: This is an amount of boosting provided by the microphone to the sound signal bytesAvailable: This reveals the number of bytes from the present position until the end of our sample data byteArray length: Lets us know the total length of our sample data byteArray position: This is the current position, in bytes, within our sample data byteArray  
Read more
  • 0
  • 0
  • 2182

article-image-flash-development-android-visual-input-camera
Packt
21 Jun 2011
7 min read
Save for later

Flash Development for Android: Visual Input via Camera

Packt
21 Jun 2011
7 min read
Camera and microphone are standard accessories on most mobile devices and Android devices are no exception to this. The present article will cover everything from accessing the camera and taking photos to recording video data. All of the recipes in this article are represented as pure ActionScript 3 classes and are not dependent upon external libraries or the Flex framework. Therefore, we will be able to use these examples in any IDE we wish. Detecting camera and microphone support in Android Nearly all Android devices come equipped with camera hardware for capturing still images and video. Many devices now have both front and rear-facing cameras. It is important to know whether the default device camera is usable through our application. We should never assume the availability of certain hardware items, no matter how prevalent across devices. Similarly, we will want to be sure to have access to the device microphone as well, when capturing video or audio data. How to do it... We will determine which audio and video APIs are available to us on our Android device: First, import the following classes into your project: import flash.display.Sprite; import flash.display.Stage; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.media.Camera; import flash.media.CameraUI; import flash.media.Microphone; import flash.text.TextField; import flash.text.TextFormat; Declare a TextField and TextFormat object pair to allow visible output upon the device: private var traceField:TextField; private var traceFormat:TextFormat; We will now set up our TextField, apply a TextFormat, and add the TextField to the DisplayList. Here, we create a method to perform all of these actions for us: protected function setupTextField():void { traceFormat = new TextFormat(); traceFormat.bold = true; traceFormat.font = "_sans"; traceFormat.size = 44; traceFormat.align = "center"; traceFormat.color = 0x333333; traceField = new TextField(); traceField.defaultTextFormat = traceFormat; traceField.selectable = false; traceField.mouseEnabled = false; traceField.width = stage.stageWidth; traceField.height = stage.stageHeight; addChild(traceField); } Now, we must check the isSupported property of each of these objects. We create a method here to perform this across all three and write results to a TextField: protected function checkCamera():void { traceField.appendText("Camera: " + Camera.isSupported + "n"); traceField.appendText("CameraUI: " + CameraUI.isSupported + "n"); traceField.appendText("Microphone: " + Microphone.isSupported + "n"); } We now know the capabilities of video and audio input for a particular device and can react accordingly: How it works... Each of these three classes has a property isSupported, which we may invoke at any time to verify support on a particular Android device. The traditional Camera and mobile-specific CameraUI both refer to the same hardware camera, but are entirely different classes for dealing with the interaction between Flash and the camera itself, as CameraUI relies upon the default device camera applications to do all the capturing, and Camera works exclusively within the Flash environment. The traditional Microphone object is also supported in this manner. There's more... It is important to note that even though many Android devices come equipped with more than one camera, only the primary camera (and microphone) will be exposed to our application. Support for multiple cameras and other sensors will likely be added to the platform as Android evolves. Using the traditional camera API to save a captured image When writing applications for the web through Flash player, or for a desktop with AIR, we have had access to the Camera class through ActionScript. This allows us to access different cameras attached to whatever machine we are using. On Android, we can still use the Camera class to access the default camera on the device and access the video stream it provides for all sorts of things. In this example, we will simply grab a still image from the Camera feed and save it to the Android CameraRoll. How to do it... We will construct a Video object to bind the Camera stream to, and use BitmapData methods to capture and then save our rendered image using the mobile CameraRoll API: At a minimum, we need to import the following classes into our project: import flash.display.BitmapData; import flash.display.Sprite; import flash.display.Stage; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.TouchEvent; import flash.media.Camera; import flash.media.CameraRoll; import flash.media.Video; import flash.ui.Multitouch; import flash.ui.MultitouchInputMode; Now we must declare the object instances necessary for camera access and file reference: private var video:Video; private var camera:Camera; private var capture:BitmapData; private var cameraRoll:CameraRoll; private var videoHolder:Sprite; Initialize a Video object, passing in the desired width and height, and add it to the DisplayList: protected function setupVideo():void { videoHolder = new Sprite(); videoHolder.x = stage.stageWidth/2; videoHolder.y = stage.stageHeight/2; video = new Video(360, 480); videoHolder.addChild(video); video.x = -180; video.y = -240; videoHolder.rotation = 90; addChild(videoHolder); } Initialize a Camera object and employ setMode to specify width, height, and frames per second before attaching the Camera to our Video on the DisplayList: protected function setupCamera():void { camera = Camera.getCamera(); camera.setMode(480, 360, 24); video.attachCamera(camera); } We will now register a TouchEvent listener of type TOUCH_TAP to the Stage. This will enable the user to take a snapshot of the camera display by tapping the device screen: protected function registerListeners():void { Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; stage.addEventListener(TouchEvent.TOUCH_TAP, saveImage); } To capture an image from the camera feed, we will initialize our BitmapData object, matching the width and height of our Video object, and employ the draw method to translate the Video pixels to BitmapData. To save our acquired image to the device, we must initialize a CameraRoll object and invoke addBitmapData(), passing in the BitmapData object we have created using Video object pixels. We will also determine whether or not this device supports the addBitmapData() method by verifying CameraRoll. supportsAddBitmapData is equal to true: protected function saveImage(e:TouchEvent):void { capture = new BitmapData(360, 480); capture.draw(video); cameraRoll = new CameraRoll(); if(CameraRoll.supportsAddBitmapData){ cameraRoll.addBitmapData(capture); } } If we now check our Android Gallery, we will find the saved image: How it works... Most of this is performed exactly as it would be with normal Flash Platform development on the desktop. Attach a Camera to a Video, add the Video to the DisplayList, and then do whatever you need for your particular application. In this case, we simply capture what is displayed as BitmapData. The CameraRoll class, however, is specific to mobile application development as it will always refer to the directory upon which the device camera stores the photographs it produces. If you want to save these images within a different directory, we could use a File or FileReference object to do so, but this involves more steps for the user. Note that while using the Camera class, the hardware orientation of the camera is landscape. We can deal with this by either restricting the application to landscape mode, or through rotations and additional manipulation as we've performed in our example class. We've applied a 90 degree rotation to the image in this case using videoHolder.rotation to account for this shift when reading in the BitmapData. Depending on how any specific application handles this, it may not be necessary to do so. There's more... Other use cases for the traditional Camera object are things such as sending a video stream to Flash Media Server for live broadcast, augmented reality applications, or real-time peer to peer chat.
Read more
  • 0
  • 0
  • 2266

article-image-getting-started-cocos2d
Packt
28 Feb 2011
8 min read
Save for later

Getting Started With Cocos2d

Packt
28 Feb 2011
8 min read
  Cocos2d for iPhone 0.99 Beginner's Guide Make mind-blowing 2D games for iPhone with this fast, flexible, and easy-to-use framework! A cool guide to learning cocos2d with iPhone to get you into the iPhone game industry quickly Learn all the aspects of cocos2d while building three different games Add a lot of trendy features such as particles and tilemaps to your games to captivate your players Full of illustrations, diagrams, and tips for building iPhone games, with clear step-by-step instructions and practical examples         Read more about this book       (For more resources on this subject, see here.) Downloading Cocos2d for iPhone Visit http://www.cocos2d-iphone.org for downloading the latest files. Search the downloads page, and there you will find the different versions available. As of this writing, Version 0.99.5 is the latest stable version. Once you have downloaded the file to your computer, uncompress the folder to your desktop, and rename it to Cocos2d. Open the uncompressed folder and take a look at its contents. Inside that folder, you will find everything you will need to make a game with Cocos2d. The following is a list of the important folders and files: Cocos2d: The bread and butter of Cocos2d. CocosDenshion: The sound engine that comes along. Cocoslive: Cocos2d comes packed with its own highscore server. You can easily set it up to create a scoreboard and ranking for your game. External: Here are the sources for Box2d and Chipmunk physics engines among other things. Extras: Useful classes created by the community. Resources: Images, sounds, tilemaps, and so on, used in the tests. Templates: The contents of the templates we'll soon install. Test: The samples used to demonstrate all the things Cocos2d can do. Tools: Some tools you may find useful, such as a ParticleView project that lets you preview how particles will look. License files: They are here in case you need to look at them. We'll start by taking a look at the samples. Time for action – opening the samples project Inside the cocos2d-iphone folder, you will find a file named cocos2d-iphone. xcodeproj. This project contains all the samples and named tests that come with the source code. Let's run one of them. Open the .xcodeproj file: In the groups and files panel you will find the source code of all the samples. There are more than 35 samples that cover all of the capabilities of Cocos2d, as shown in the following screenshot: Compile and run the SpriteTest: This project comes with a target for each of the available tests, so in order to try any of them you have to select them from the overview dropdown. Go ahead and select the SpriteTest target and click on Build and Run. If everything goes well the test should start running. Play a little with it, feel how it behaves, and be amazed by the endless possibilities.   What just happened?   You have just run your first Cocos2d application. If you want to run another sample, just select it by changing the "Active target". When you do so, the "active executable" should match to the same; if it doesn't select it manually by selecting it from the overview dropdown box. You can see which "active target" and "active executable" is selected from that overview dropdown box, they should be selected. Installing the templates Cocos2d comes with three templates. These templates are the starting point for any Cocos2d game. They let you: Create a simple Cocos2d project Create a Cocos2d project with Chipmunk as physics engine Create a Cocos2d project with Box2d as physics engine Which one you decide to use for your project depends on your needs. Right now we'll create a simple project from the first template. Time for action – installing the templates Carry out the following steps for installing the templates: Open the terminal. It is located in Applications Utilities | Terminal|. Assuming that you have uncompressed the folder on your desktop and renamed it as Cocos2d, type the following: cd desktop/Cocos2d ./install_template.sh You will see a lot of output in the terminal (as shown in the following screenshot); read it to check if the templates were installed successfully. If you are getting errors, check if you have downloaded the files correctly and uncompressed them into the desktop. If it is in another place you may get errors. We just installed the Xcode templates for Cocos2d. Now, each time you create a new project in Xcode, you will be given the choice of doing it by using a Cocos2d application. We'll see how to do that in a moment. Each time a new version of Cocos2d is released, there is a template file for that version. So, you should remember to install them each time. If you have a lot of older templates and you want to remove them, you can do so by going to Developer/Platforms/iPhoneOS. platform/Developer/Library/Xcode/Project Templates/Application and deleting the respective folder.   What just happened?   Templates are very useful and they are a great starting point for any new project. Having these templates available makes starting a new project an easy task. You will have all the Cocos2d sources arranged in groups, your AppDelegate already configured to make use of the framework and even a simple starting Layer. Creating a new project from the templates Now that you have the templates ready to use, it is time to make your first project. Time for action – creating a HelloCocos2d project We are going to create a new project named HelloCocos2d from the templates you have just installed. This won't be anything like a game, but just an introduction on how to get started. The steps are as follows: Open Xcode and select File New project| (Shift + cmd + N). 2. Cocos2d templates will appear right there along with the other Xcode project templates, as shown in the following screenshot: Select Cocos2d-0.99.1 Application. Name the project HelloCocos2d and save it to your Documents folder. Once you perform the preceding steps, the project you just created should open up. Let's take a look at the important folders that were generated: Cocos2d Sources: This is where the Cocos2d source code resides. Generally, you won't touch anything from here unless you want to make modifications to the framework or want to know how it works. Classes: This is where the classes you create will reside. As you may see, two classes were automatically created, thanks to the template. We'll explore them in a moment. Resources: This is where you will include all the assets needed for your game. Go ahead and run the application. Click on Build and go and congratulate yourself, as you have created your first Cocos2d project. Let's stop for a moment and take a look at what was created here. When you run the application you'll notice a couple of things, as follows: The Cocos2d for iPhone logo shows up as soon as the application starts. Then a CCLabel is created with the text Hello World. You can see some numbers in the lower-left corner of the screen. That is the current FPS the game is running at. In a moment, we'll see how this is achieved by taking a look at the generated classes.   What just happened?   We have just created our first project from one of the templates that we installed before. As you can see, using those templates makes starting a Cocos2d project quite easy and lets you get your hands on the actual game's code sooner. Managing the game with the CCDirector The CCDirector is the class whose main purpose is scene management. It is responsible for switching scenes, setting the desired FPS, the device orientation, and a lot of other things. The CCDirector is the class responsible for initializing OpenGL ES. If you grab an older Cocos2d project you might notice that all Cocos2d classes have the "CC" prefix missing. Those were added recently to avoid naming problems. Objective-c doesn't have the concept of namespaces, so if Apple at some point decided to create a Director class, those would collide. Types of CCDirectors There are currently four types of directors; for most applications, you will want to use the default one: NSTimer Director: It triggers the main loop from an NSTimer object. It is the slowest of the Directors, but it integrates well with UIKit objects. You can also customize the update interval from 1 to 60. Mainloop Director: It triggers the main loop from a custom main loop. It is faster than the NSTimer Director, but it does not integrate well with UIKit objects, and its interval update can't be customized. ThreadMainLoop Director: It has the same advantages and limitations as the Mainloop Director. When using this type of Director, the main loop is triggered from a thread, but it will be executed on the main thread. DisplayLink Director: This type of Director is only available in OS 3.1+. This is the one used by default. It is faster than the NSTimer Director and integrates well with UIKit objects. The interval update can be set to 1/60, 1/30, or 1/15. Those are the available Directors, most of the times you will not need to make any changes here.
Read more
  • 0
  • 0
  • 3190
article-image-cocos2d-iphone-handling-accelerometer-input-and-detecting-collisions
Packt
30 Dec 2010
4 min read
Save for later

Cocos2d for iPhone: Handling Accelerometer Input and Detecting Collisions

Packt
30 Dec 2010
4 min read
  Cocos2d for iPhone 0.99 Beginner's Guide Make mind-blowing 2D games for iPhone with this fast, flexible, and easy-to-use framework! A cool guide to learning cocos2d with iPhone to get you into the iPhone game industry quickly Learn all the aspects of cocos2d while building three different games Add a lot of trendy features such as particles and tilemaps to your games to captivate your players Full of illustrations, diagrams, and tips for building iPhone games, with clear step-by-step instructions and practical examples         Read more about this book       (For more resources on Cocos2d, see here.) Handling accelerometer input Now that we have our three basic elements roughly defined, let's focus on the player's interaction with the hero. We will start by allowing the player to move the hero using the device's built-in accelerometer. The accelerometer opens a new world of interaction between the user and the device, allowing for a lot of interesting uses. There are already lots of applications and games that use this feature in innovative ways. For example, in the game Rolando, players have to roll the main character around using the accelerometer, and here we will be doing something similar to that. The accelerometer gives you data of the current tilting of the device in the three axes, that is the x, y, and z axes. Depending on the game you are making, you will be needing all that data or just the values for one or two of the axis. Fortunately, Apple has made it very easy for developers to access the data provided by the accelerometer hardware. Time for action – moving your hero with the accelerometer We have to add a few lines of code in order to have our hero move. The end result will be the hero moving horizontally when the user tilts the device to the left or to the right. We will also do some checkovers, in order to avoid the hero moving out of the screen. The first step involved in using the accelerometer is to enable it for the CCLayers that want to receive its input. Add the following line of code to the GameLayer's init method: self.isAccelerometerEnabled = YES; Then we have to set the update interval for the accelerometer. This will set the interval at which the hardware delivers the data to the GameLayer. Add the following line afterwards: [[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 60)]; Now that our GameLayer is prepared to receive accelerometer input, we just have to implement the method that receives and handles it. The following is the method that receives the input and makes our hero move. Add it to the GameLayer class: - (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration{ static float prevX=0, prevY=0; #define kFilterFactor 0.05f float accelX = (float) acceleration.x * kFilterFactor + (1- kFilterFactor)*prevX; prevX = accelX;//If the hero object exists, we use the calculated accelerometer values to move him if(hero) {//We calculate the speed it will have and constrain it so it doesn't move faster than he is allowed to float speed = -20 * -accelX; if(speed > hero.movementSpeed) speed = hero.movementSpeed; else if(speed < -hero.movementSpeed) speed = -hero.movementSpeed;//We also check that the hero won't go past the borders of the screen, if he would exit the screen we don't move it if((accelX >0 || hero.mySprite.position.x >hero.mySprite.textureRect.size.width / 2) && ( accelX <0 ||hero.mySprite.position.x <320- hero.mySprite.textureRect.size.width / 2)) [hero.mySprite setPosition:ccp(hero.mySprite.position.x +speed,hero.mySprite.position.y)]; }} Run the game now. You should be able to move the hero by tilting you device, as shown in the following screenshot: The iPhone simulator does not provide a way to simulate accelerometer input, so you won't be able to test it in there; it won't move at all. What just happened? Accelerometer input can be achieved quite easily and fast. In our example, we just used the x component of the accelerometer input to handle the hero's position. The accelX variable holds the current value of the x component. This value ranges from -1 to 1, so we multiply it by the speed of the hero, then we just add that result to the current position of the hero, giving the sense of motion. We are also checking to make sure that the hero is not going off the screen before applying that movement.
Read more
  • 0
  • 0
  • 1899

article-image-cocos2d-iphone-adding-layers-and-making-simple-pause-screen
Packt
30 Dec 2010
6 min read
Save for later

Cocos2d for iPhone: Adding Layers and Making a Simple Pause Screen

Packt
30 Dec 2010
6 min read
Adding more layers to scenes As we have discussed before, a scene can contain any number of layers you want. Well, as long as performance is not an issue. As CCLayer inherits from CCNode, it can be added as the child of CCScenes or other CCLayers, allowing you to organize your content in a nice fashion. There are three types of CCLayers that you can use and combine in your games. They are as follows: CCLayer: We have been using them forever. Besides all the features inherited from CCNodes, they can receive touches and accelerometer input. CCColorLayer: They inherit from CCLayer so besides being able to receive touches and accelerometer input, their opacity and RGB colors can be changed. CCMultiplexLayer: It inherits from CCLayer and can have many children, but only one will be active at any given time. You can switch between those children. In the following examples, we will be creating some CCLayers in different ways to achieve different results. Time for action – creating a HUD to display lives and the score We will begin by building a simple Heads Up Display (HUD) for our game. Its purpose is to show some useful data about the current state of the game to the player. The idea behind making the HUD into a new layer is to simplify the logic of the GameLayer. This way, the GameLayer will only handle stuff of the game itself while leaving the HUD logic to the HUDLayer. In our game, the HUD will display the remaining lives, score, remaining bombs, and anything you want to display later. Once it is done, all we need to do in the GameLayer is send a message so the HUDLayer gets updated. The first step in creating the HUD is to add a new file to the project. In the Xcode project, select File | New file and add a new Objective-C class. Rename it as HUDLayer. Replace the contents of the HudLayer.h with the following lines: #import <Foundation/Foundation.h> #import "cocos2d.h" #import "GameScene.h" @interface HudLayer : CCLayer { CCBitmapFontAtlas * level; CCBitmapFontAtlas * score; CCBitmapFontAtlas * bombs; NSMutableArray * lives; } @property (nonatomic,retain) CCBitmapFontAtlas * level; @property (nonatomic,retain) CCBitmapFontAtlas * score; @property (nonatomic,retain) CCBitmapFontAtlas * bombs; @property (nonatomic,retain) NSMutableArray * lives; @end Do the same with the contents of the HudLayer.m file: #import "HudLayer.h" @implementation HudLayer @synthesize lives,bombs,score,level; - (id) init { if ((self = [super init])) { CCSprite * background = [CCSprite spriteWithFile:@"hud_background.png"]; [background setPosition:ccp(160,455)]; [self addChild:background]; lives = [[NSMutableArray arrayWithCapacity:3]retain]; for(int i=0;i<3;i++) { CCSprite * life = [CCSprite spriteWithFile:@"hud_life.png"]; [life setPosition:ccp(18+ 28*i,465)]; [self addChild:life]; [lives addObject:life]; } CCSprite * bomb = [CCSprite spriteWithFile:@"hud_bomb.png"]; [bomb setPosition:ccp(18,445)]; [self addChild:bomb]; GameLayer * gl = (GameLayer *)[self.parent getChildByTag:KGameLayer]; level = [CCBitmapFontAtlas bitmapFontAtlasWithString:@"Level 1" fntFile:@"hud_font.fnt"]; [level setAnchorPoint:ccp(1,0.5)]; [level setPosition:ccp(310,465)]; [level setColor:ccBLACK]; [self addChild:level]; score = [CCBitmapFontAtlas bitmapFontAtlasWithString:@"Score 0" fntFile:@"hud_font.fnt"]; [score setAnchorPoint:ccp(1,0.5)]; [score setPosition:ccp(310,445)]; [score setColor:ccBLACK]; [self addChild:score]; bombs = [CCBitmapFontAtlas bitmapFontAtlasWithString:@"X3" fntFile:@"hud_font.fnt"]; [bombs setAnchorPoint:ccp(1,0.5)]; [bombs setPosition:ccp(47,440)]; [bombs setColor:ccBLACK]; [self addChild:bombs]; } return self; } - (void) dealloc { [super dealloc]; [lives release]; } @end You can find the images and the font used above in the companion files at Support. What we have to do now is load this new layer and add it as a child of the GameScene. Change the init method of the GameScene class to look like the following: - (id) init { self = [super init]; if (self != nil) { [self addChild:[GameLayer node] z:0 tag:KGameLayer]; //kGameLayer defined in the GameScene.h file. #define kGameLayer 1 [self addChild:[HudLayer node] z:1 tag:KHudLayer]; //kHudLayer defined in the GameScene.h file. #define kHudLayer 2 } return self; } The only thing missing now is to make some changes here and there to be able to update the HUDLayer with the actual state of the game. Let's update the score and remaining lives, for now. Change the loseLife method of the GameLayer class: -(void)loseLife { self.lives--; HudLayer * hl = (HudLayer *)[self.parent getChildByTag:KHudLayer]; CCSprite * live = [hl.lives objectAtIndex:self.lives]; [live setVisible:NO]; if(self.lives ==0) { [self resetGame]; //LOSE THE GAME //GO TO GAME OVER LAYER } } Add the resetGame method: -(void)resetGame { HudLayer * hl = (HudLayer *)[self.parent getChildByTag:KHudLayer]; for(CCSprite * c in hl.lives) { [c setVisible:YES]; } self.level=1; [hl.level setString:@"Level 1"]; self.score=0; [hl.score setString:@"Score 0"]; self.bombs =3; [hl.bombs setString:@"X3"]; lives = STARTING_LIVES; } These methods will handle the displaying of the remaining lives. Finally, modify the Enemy class's destroy method, so it updates the score label instead of logging the score to the console: -(void)destroy { [self reset]; [theGame setScore:theGame.score+100]; HudLayer * hl = (HudLayer *)[theGame.parent getChildByTag:KHudLayer]; [hl.score setString:[NSString stringWithFormat:@"Score %d",theGame.score]]; } Run the game. You should see a HUD at the top of the screen (as shown in the following screenshot) with all the actual information about the state of the game. Destroy some enemies to see the score updated and lose some lives to see the "lives" icons disappear. What just happened? We just went through the steps needed to create a new layer, adding it to the scene and updating its contents. Our new layer just holds some information of the game state and displays it to the player. In order to achieve that we just added a few CCSprites and CCBitmapFontAtlases which get updated when needed. Once the HudLayer class was created we added it to the GameScene over the GameLayer, so its contents are always shown on top of the GameLayer's ones. We also provided a tag for both layers, as we will need to access them from other places. We could also have added a reference to the other layer inside them. That is all what we need to do in order to add more layers to a scene. The rest of the code just handles the updating of the contents of the HudLayer. When the player hits an enemy, a score is awarded. Then the label placed in the HUD is updated. When the hero is hit and a life is lost, we just turn the corresponding icon's visibility off, then when the game is reset we turn all of them on.
Read more
  • 0
  • 0
  • 2511