Tuesday, September 20, 2011

Emulating an SD card on the Android Emulator

Many a times, we need the SD card to store data. But how can one do this in the emulator? Well, here's how.
It's a simple 2 step process:
1. Create an image of the SD card
On the command prompt, navigate to the "\Android SDK\tools" directory.
eg. D:\AndroidDev\Android SDK\tools>
Give the command
mksdcard 128M MySDCard
That's it. Your SD card image is ready.

2. Using the SD card in eclipse
In the Package explorer, right click on your project and select "Run As>Run Configurations..."

In the right panel, select Target tab.
In the text box provided for Additional Emulator Command Line Options, enter the following:
-sdcard <full path to your sd card image file>

Once this is done, click on Run and the SD card is accessible!
On subsequent runs, we do not need to set up the command line option again. It's just to be done ONCE.

Tuesday, September 6, 2011

Your friend, Android!

While learning a new language/ platform, it’s imperative to get oneself acquainted with the terminology. It’s analogous to making a new friend and improving your friendship. When we make friends with a new person, we try to find out quite a few attributes of that person apart from his name. If we want the friendship to thrive, we improve on it by knowing more about the friend, eg. his house, his family, the mobile he uses, his hobbies, etc. The same applies to learning Android. So let’s get acquainted with our new friend “Android”!!!

Here are a few attributes which will help us to get better acquainted with our friend.
1. Activity
An Activity is a single screen of the User interface. This Activity can hold a hierarchy of views to give the UI the functionality it needs.
eg. For an email-application, we can have 3 Activities:
1. To log in.
2. To list all the mails we have received (and to interact with them).
3. To write and send an email.

All the above Activities are related, but they work separately on their own.

2. View

This class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. The Views are placed inside the Layouts and with them we can create the most simple of UI to the most complex one. Android gives us the choice to work with XML to create UI. This is a good way to separate functionality from User Interface.
3. Layout

A Layout is a container for elements in the User Interface. We can declare our layout in two ways:

·         Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.
·         Instantiate layout elements at runtime. Our application can create View and ViewGroup objects (and manipulate their properties) programmatically.

Every time we define a ‘.xml’ file with a specific user interface, we need to use these elements to hold hierarchy view tree. We have different layouts like RelativeLayout and LinearLayout, depending on its properties and relationship with the elements its holds. Layouts can be nested one inside another.
4. Service

A Service runs in the background and doesn’t have UI.
A service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component, say activity, can start a service and it will continue to run in the background even if the user switches to another application.

Additionally, a component can bind to a service to interact with it and even perform inter process communication (IPC). eg., a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
A service can essentially take two forms:
1.       Started
2.       Bound
We will discuss each of these in the later posts.
 An example of Service can be a system that notifies the user when a sms has been received in the mobile.

5. Content provider
With content providers, we can access to any data stored in the device form an application. This data can be stored in files or is the SQLite database. They're the only way to share data across applications; there's no common storage area that all Android packages can access. Android ships with a number of built-in content providers eg. Contact information. They are listed in the android.provider package.

6. Intents
Objects of type "android.content.Intent" are used to send asynchronous messages within your application or between applications. Intents allow to send or receive data from and to other activities or services. They also allow to broadcast that a certain event has occurred. Intents are also used to start one activity from another.

Intents are powerful because they allow for loose coupling of applications.
Android supports implicit as well as explicit intents, the details of which we shall discuss later.

7. Events

An Event is something that occurs form the “outside”. It is something we don’t control, the time of which we cannot predict. When an event occurs, our application might want to do some processing based on the event that has occurred. For that we use the Event controllers. For each event that can happen, we can define how the system is going to react to it.

A common event is onTouch Event which occurs when the screen is touched. We define event listeners to capture this event and do the processing.

8. Application Resources

Resources are the external elements we use in our applications. They are placed in the “res” folder in the project and they can be images, icons, music files, videos.
This folder also contains the various string resources used in the application, various layout files and themes, all stored as .xml files. Once resources are compiled, they are available in Java code using the "R.java" file.

9. Data Storage

Android provides several options to save persistent application data. The solution we choose depends on our specific needs, such as the privacy level and the size of the data.

Data storage options:
a.       Shared Preferences
       Use this to store private primitive data in key-value pairs.
b.       Internal Storage
       Use this to store private data on the device memory. Data size is one attribute that is to be
        kept in mind here.
c.       External Storage
       Use this option to store public data on the shared external storage. i.e. the sd card.
d.       SQLite Databases
       Use this to store structured data in a private database.
e.   Network
      You can also use the Internet to store and receive data, whether it's an SQLite database, or just a
       simple text file.

10. Security
Android is a privilege-separated operating system, in which each application runs with a distinct system identity (Linux user ID and group ID). Parts of the system are also separated into distinct identities. Linux thereby isolates applications from each other and from the system. Android basically deals with Inter Component Communication. Security encompasses a variety of topics like Application signing, file access, creating and using ‘Permissions’, etc. which we will cover up in detail later on.

11. Using Web Services
One of the most powerful aspects of any mobile application for a smart phone is that it can connect to the Internet. By connecting to the Internet the application can offer much more value to the user since it becomes an interface for a web-based component, e.g. using Twitter APIs to create a Twitter application so that you can get your Twitter updates without having to open the mobile browser. Android offers many options to use web services. We shall discuss these soon.

There. That’s a good enough introduction to our new friend. The more you try to get to know about these components, the better you will befriend Android. J

Friday, July 22, 2011

The sensors at your disposal!!!

As we all know, mobile phones have come a long way from being a device for making calls and sending text messages to becoming smartphones. One of the important factors that make these phones ‘SMART’ is the way these phones leverage data received by the various sensors built in the phone itself. Let us see a few of these sensors and technologies.

1. GPS – The GPS (Global Positioning System) is a space based global navigation satellite system that provides location and time information in any weather, anywhere on Earth. This is one of the oldest technologies used, work on which started way back in 1973. It was realized by the U.S. Department of Defense, and currently there are 24 satellites that make up the GPS space segment are orbiting the earth about 12,000 miles above us.
This isn’t a sensor built in the device, there’s just a GPS receiver in the device. Nevertheless, with the mobile phones becoming smart, your mobile phone can itself become a GPS device, unlike the old days where one had to have a separate GPS device.
Usage – Location based apps are the best apps to leverage the GPS.
eg. Google maps, places, Where To Eat, GPS Essentials, GPS Test, etc.

2. Proximity Sensor - A proximity sensor is a sensor able to detect the presence of nearby objects without any physical contact. It is exactly what it name suggests. It measures the proximity of objects near it. i.e. how near or far an object is from the sensor.
A proximity sensor often emits an electromagnetic or electrostatic field, or a beam of IR radiation, and looks for changes in the field or return signal. The object being sensed is often referred to as the proximity sensor's target. Different proximity sensor targets demand different sensors. For example, a capacitive or photoelectric sensor might be suitable for a plastic target; an inductive proximity sensor requires a metal target. The maximum distance that this sensor can detect is defined "nominal range".
A proximity sensor adjusted to a very short range is often used as a touch switch. A proximity sensor is divided in two halves and if the two halves move away from each other, then a signal is activated.
Usage – Earlier used in rear bumpers of cars to assist while parking. Now used in many smartphones to detect how far the phone is from the user. Eg. During a call, when the user holds the phone near his/ her ear, the proximity sensor deactivates the screen. On taking the phone away from the ear, the screen is re-activated.

3. Ambient light sensor - Ambient light sensors are included in many laptops and cell phones to sense the environment lighting conditions, allowing for adjustment of the screen's backlight to comfortable levels
for the viewer. The range of "comfortable levels" is dependent on the room's light.
Usage - Understandably, a screen's brightness needs to increase as the ambient light increases. What is less obvious is the need to decrease the brightness in lower light conditions-for comfortable viewing and to save battery life.
Other than this, the ambient light sensor is also used for improving the quality of photos that are clicked from the phone camera in a dimly lighted area.

4. Accelerometer - An accelerometer is an electromechanical device that will measure acceleration forces. These forces may be static, like the constant force of gravity pulling at your feet, or they could be dynamic - caused by moving or vibrating the accelerometer. By measuring the amount of static acceleration due to gravity, you can find out the angle the device is tilted at with respect to the earth. By sensing the amount of dynamic acceleration, you can analyze the way the device is moving. At first, measuring tilt and acceleration doesn't seem all that exciting. However, engineers have come up with many ways to make really useful products using them.

An accelerometer can help your project understand its surroundings better. Is it driving uphill? Is it going to fall over when it takes another step? Is it flying horizontally or is it dive bombing your professor? A good programmer can write code to answer all of these questions using the data provided by an accelerometer
High g accelerometers are the industry standard way of detecting car crashes and deploying airbags at just the right time.

A number of smartphones use accelerometers to align the screen depending on the direction the device is held, for example switching between portrait and landscape modes.
It is also useful for auto image rotation, motion-sensitive games, and to correct shake when taking photographs.
Usage – Many apps like Shake Them All, Labyrinth Lite leverage the accelerometer.
You can find a nice tutorial to start using the accelerometer in your apps here

5. Gyroscope - An accelerometer measures acceleration. A 3-axis accelerometer will tell you the orientation of a stationary platform relative to earth's surface, once that platform starts moving, however, things get more complicated. If the platform is in free-fall, it will show zero acceleration. If it is accelerating in a particular direction, that acceleration will simply be added to whatever acceleration is being provided by gravity, and you will not be able to distinguish
Here’s where the gyroscope comes in.

A gyro measures rate of rotation around a particular axis. If a gyro is used to measure the rate of rotation around the aircraft roll axis, it will measure a non-zero value as long as the aircraft is rolling, but measure zero if the roll stops.
So, in a nutshell: Accelerometers are right in the long term but wrong (noisy) in the short term. Gyros are right in the short term but wrong (drifiting) in the long term. You need both--each to calibrate the other--to be right all the time.
I found a good video tutorial that compares the two sensors. The video is by InvenSense, who made the Wii MotionPlus, using Gyroscopes and Accelerometers to capture precise human hand movement.

Usage - Firing Range is one of the best apps that makes use of both the sensors. Do have a look at it.
Asphalt 5 is another great example of how the motion sensors can be leveraged in applications.
Not to mention the very famous ANGRY BIRDS…

6. Magnetometer
is a measuring instrument used to measure the strength and/or direction of the magnetic field, produced either in the laboratory or existing in nature.
Usage - This one allows the phone to be used as a precise compass. Eg. Super compass and 3D compass

These are but a few uses of the sensors. A lot of research is being carried out to use these sensors in the health care industry, apart from games and apps. There’s a lot of scope to leverage the data generated form these sensors. It’s up to you what you make of these vast resources of data available literally at your fingertips. :-)

Saturday, April 30, 2011

Future of web dev. - HTML5

So why is there so much hype about HTML5? It’s a really big deal, especially for mobile browsers and “on the go” Web users. It is predicted that HTML5 will standardize many important use cases for Mobile Web browsing that were previously implemented using proprietary APIs.
HTML 5 isn’t an officially ratified standard ….yet. The spec continues to edge closer to completion, however, and when combined with JavaScript and CSS3, HTML5 can do some really incredible things.This is particularly true for mobile devices. A basic requirement for any modern mobile OS is the inclusion of a modern HTML5-compliant web browser. The leading modern mobile platforms (iOS and Android) both use WebKit as their bases. BlackBerry and Palm are also using WebKit. Also Microsoft’s Steve Ballmer quoted at his key note at MWC 2011 “IE9 which will be coming soon for WP7, will deliver a dramatically enhanced web browser experience thanks to graphics and hardware acceleration that'll make the most of what your handset has to offer.”
What this means is that out of the box, modern smartphones and tablets support the features that make HTML5 so special. It means a big step towards platform independence for the developers.

HTML5 Features for the Mobile
HTML5 is great news for the mobile market. It promises the mobile users:
- richer Web applications
- improved usability
- rendering of rich Web content from third-party plug-ins
- testable, cross-platform and standards-based interfaces for content development
The new features of HTML5 standardize use cases and technologies that are common in smartphone-optimized Mobile Web applications. In today’s Mobile Web of XHTML-MP or HTML 4 documents, these incredible features are implemented using proprietary devices and browser APIs. With HTML5, advanced Web application features are available in all mobile browsers supporting the markup language, using the same standard syntax and displaying the same standard behavior.
Let’s look at each of these features in detail.

1. Location Awareness

HTML5’s GeolocationAPI makes the mobile’s geographic location available to a Web application. Previously, obtaining device location was only possible using proprietary JavaScript extensions or server-side integration with a mobile operator API. The API enables repeated location updates by registering callback functions.
Here is an example of how the API can be used for repeated location updates:
function updatePosition(position) {
// Latitude and longitude are available as member variables
varcurrentLatitude = position.coords.latitude;
varcurrentLongitude = position.coords.longitude;
}

// Request repeated updates.This method calls back repeatedly to the
//updatePosition() function until cancelled using clearWatch(), below.

varwatchId = navigator.geolocation.watchPosition(updatePosition);

// Cancel the geographic position updates.
functioncancelPositionUpdates() {
navigator.geolocation.clearWatch(watchId);
}

2. 2D Canvas Animation

The new <canvas> element and JavaScript 2D Canvas API allow two-dimensional drawing, graphics and …. animations!!!
Cross-platform games thus become possible in mobile browsers.
Here is an example of a canvas element:

<canvas id="newCanvas" width="300" height="400" />
and an example of the 2D Canvas API used to draw an image inside the canvas:
// Obtain a reference to the canvas element
var canvas = document.getElementById('newCanvas');

// Clear the canvas
canvas.setAttribute('width', '400');

// Draw an image on the canvas.
// 'myImage' is a reference to an existing image.
canvas.drawImage(myImage, 10, 10, 100, 50);

3. Web Storage API in HTML5

The Web Storage API allows documents to persistently store data in a mobile browser. Mobile browsers can write data in one browsing session and read it in the next session.

4. Offline Application Caching in HTML5

HTML5 documents use a manifest to list all dependent external resources (i.e. CSS files, JavaScript libraries, images etc.). This is probably one of the best features for mobiles since their browsers use the manifest to cache an entire Web application for offline use, allowing mobile users to interact with a Web app while roaming in and out of coverage areas.

5. Native Audio and Video Controls in HTML5

New <video> and <audio> elements embed multimedia into a Web document without using third-party browser plug-ins. Mobile browsers may natively control multimedia display, codecs and user interfaces.
However, HTML5 does not resolve certain problems of web development, including:
  • Fragmentation: Too many vendors implement mobile browsers, creating a fragmented marketplace and forcing developers to adapt Web content to play to browser strengths and avoid browser weaknesses.
  • Browsers Bugs: As with any Web standard, HTML5 features may be incompletely or incorrectly implemented in a mobile browser.
  • Rushing with HTML5: Mobile browsers may support HTML5 too quickly, implementing features or syntax that end up changed or cut from the final standard.
  • Forgetting the Mass Market: Many popular Mobile Web sites use simple markup to quickly provide chunks of relevant information to users. Upgrading these Mobile Web sites to use HTML5 (without implementing content adaptation) could cut off access to millions of users with older, Web-accessible mobile browsers.
Smartphones provide an excellent platform for rolling out HTML5 applications to the Mobile Web users. However, the majority of mobile subscribers still use non-smartphone devices with no ability to update the browser or operating system. Developers must use content adaptation principles to include advanced HTML5 elements only the target mobile browser is known to support HTML5. Content adaptation ensures a satisfactory Mobile Web experience for all mobile users.

For beginners, there is a good book for diving into HTML 5 :
HTML5 – Up and Running
Author – Mark Pilgrim

Tuesday, March 22, 2011

Native apps vs. Web apps

Today’s smartphones have evolved from devices which had the primary purpose of making calls and sending text messages to devices which can be transformed into a gaming machine, a satellite navigation system or a newspaper which also plays videos.
The shift has fundamentally altered the way consumers think about what a phone is and how they use it, so much so that its primary functions (calling and texting) have become secondary.
This evolution is currently headed by the iPhone which currently has over 3,50,000 apps on its app store. Not far behind is the Android market place which houses over 1,40,000 apps. Also, Nokia, RIM and Microsoft provide similar apps.
So with apps being a hot and lucrative market and a number of competing platforms to choose from, how do we go about developing it? There are basically two choices when it comes to developing a mobile app.

1. Create a native application
A native app is an app which is installed and run on the mobile and is developed using the device’s SDK. As the name suggests, these applications run only on one platform. i.e. an app which is developed for Android phones will run only on those phones and not on iPhones. So developers need to develop a different app for each platform. Once developed, the app can then be sold on its respective market place such as the Apple’s App Store, Google’s Android Market, Nokia’s Ovi Store.

2. Create a mobile web application
A mobile app is a web-based application which runs in the browser of the mobile. There’s no special deployment necessary. It only requires a browser to execute. The goal is to build a web app which is usable by most (if not all) of the different types of mobile platforms. However, in practice this isn’t particularity easy – yet.
Suppose one needs to develop a mobile version of their site, then they have an option of not doing anything and hoping that their already existing site is useable enough on mobile browsers as well. This depends on how the site was built, which browser is being used to view it properly, etc. There is a possibility that a large number of users may get a less than ideal experience. We’ll cover the difference between mobile web sites and desktop web sites in detail soon.

Both web and native apps have their pros and cons, and the choice often has to be made based on what you want your app to do and what your users should expect.

Going Native
Developing a native app will provide benefits in its performance, given that it is tightly integrated with all the device’s features and its API’s. Native apps enhance user experience by utilizing the full capabilities of a device.
Native apps have certain advantages like:
  • They can use all of the device’s features such as its camera, GPS, compass, file system etc.
  • They can be sold through a marketplace such as the App Store or Android Marketplace.
  • They have superior performance compared with a typical web app.
  • Don’t necessarily need to be connected to a 3G or Wi-Fi network.
  • They’re not running in a browser. So there’s no restriction on the types of application that can be developed.

Because a native app isn’t restricted to running in a browser they can do some pretty intensive things such as an augmented reality app or full 3D games. Neither of this is currently be possible with a web app.
But there are downsides, too:
  • Higher development cost and longer lead time.
  • Very little portability across platform – if you want your app to run on both the iPhone and Android, it means building two separate versions.
  • Maintenance and upgrade costs.

So if we want to do anything that takes full advantage of a device’s capabilities, or do anything custom or unique, then we’ll go for a native app.
However, the issue of building and deploying on many different platforms mean the overall cost may be high. And this is where web apps look like a great alternative: A web based app should be able to run on any device with a browser.

Going the web app way
A web app is an application that is accessed over a network.
Everything which we interact with on the internet is a web app in one form or another: Facebook, Twitter, Flickr – all in a broad sense are web apps.
The major advantage of web apps is mobility. They can be used on-the-go (wherever you are, via almost any browser).
No downloading, no software updates and no uninstalling!!! Just open a browser window, type the URL and hit Go. Add that to fact that almost all mobile phones now-a-days have a web browser means that we have potentially large number of users who are already familiar with how to get to and use the app.
However web development for mobile devices is still in the developing phase and it is difficult to do quite a few things which would be straightforward in a native application (like accessing the camera).
Even though currently it’s not possible to build a web app that will do everything that a native app does, for some situations a mobile app is perfect. There’s some great work going in with jQTouch which is a tool that makes it easier to build mobile web apps for both the iPhone and Android, that look and feel more like a native application.
There’s also PhoneGap, which enables a web app to be packaged and deployed as a native app for the iPhone, Blackberry and Android.
Also with the advent of HTML5, the gap between web apps and native apps seems to be reducing.

With these types of tools emerging, and the mobile phones themselves becoming more powerful, it’s not long before web apps will become the choice for a larger percentage of mobile apps.
The fact that Apple (iPhone), Google (Android), Palm (Pre), Nokia and RIM (Blackberry) are all backing the open source WebKit engine to power their web browsers, proves that the biggies are taking a major step in getting a consistent experience across multiple devices.
Very soon, web apps will stand true to the principle: write once, run anywhere.
In the next couple of years most, if not all, mobile platforms will have support for the following advanced features all of which will drasticly change both what web apps are capable of and what users will expect from them:
  • Pure web-based 3D graphics via WebGL.
  • Standardized 2D graphics and animation (slick animation and graphics are trademarks of native applications’ rich interfaces).
  • Standardized video and audio support (no plugins required to watch movies or listen to streaming music).
  • Local storage and SQL databases ( data can be stored within the web app itself so one doesn’t always require an internet connection to use it. Google Apps provide this features already using Google Gears).
  • Manifests and offline resource caching.( Photos, videos are still accessible even if you go offline).
Thus the future is bright for the web app development.

Monday, February 28, 2011

First Android app - Hello World!

In the previous blog, we set up the environment for creating Android projects
using Eclipse. We also saw how to set up a virtual device. After we create the
AVD(Android Virtual Device), we are ready to create our first program.
As is the tradition, the first program in any language is a small Hello World
program.

So let’s get started.
  1. Start Eclipse.
  2. Select File > New > Project.
  3. In the New Project dialog, select Android > Android
    Project.
  4. Click Next.



5. Fill in the details as shown below and click Finish.


 6. Our android project is now ready. It should be visible in the “Package
Explorer” on the left hand side.



Let’s see the folders of the project:
a.     src
This folder contains the Java source files that you will be creating. In the
screenshot you can see the ‘activity’ files that were created for the sample
project i.e. HelloAndroid. The files inside this  folder will be organized
according to the package structure. This is similar to the /src folder which is
present in any normal Java project.
b.     gen
This is also a source folder, but it contains Java source files that are
automatically generated by the android platform.
“R.java” is a generated class which contains references to resources of the
“res” folder in the project. These resources are maintained in the “res”
directory and can be values, menus, layouts, icons or pictures or animations.
For example a resource can be an image or an XML files which defines
strings.
If you create new resources, the corresponding reference is automatically
created in “R.java”. The references are static int values. The Android system
provides methods to access the resources. eg. to access a String with the
reference id “R.string.yourString” use the method
getString(R.string.yourString)); Please do not try to modify “R.java”
manually.

While the directory “res” contains structured values which are known to the
Android platform, the directory “assets” can be used to store any kind of data.
In Java you can access this data via the AssetsManager and the method
getAssets().
c.      /Android {version Number}
This folder contains the libraries (jars) needed for the project. In the
screenshot, you can see that it contains the framework jar file. This is similar
to the /lib folder which is present in any normal Java project.

d.     /res
This directory contains all the external resources (images, data files etc)
that are used by the android application. These external resources (content)
will be referenced in the android application.

This contains the following sub-folders
  • /res/drawable
  • /res/layout
  • /res/Values
i.        /res/drawable
This folder contains all images, pictures etc. If you want to include an
image or an icon in your android application, then you will be placing it in
this folder.
ii.      /res/layout
This folder contains the UI layouts that will be used in the project. These
UI layouts are stored as XML files. You can read more about it here.
iii.     /res/Values
This folder contains XML files which contain key values pairs that
will be referenced in the application. These XML files declare Arrays, colors,
dimensions, strings etc.
The main idea of having these values in a separate XML file is that the
values can be used based on the locale without actually changing the source
code. 
eg.  the messages in the application can be displayed in different languages
based on the use locale.
e.        /assets
This folder contains external resources used in the application like the /res
folder. But the main difference is that the resources are stored in raw format
and can be read only programmatically.

AndroidManifest.xml
This is an XML file which contains meta information about the android
application and is important file for every android application project. It
contains information about various activities, views, services etc. It also
contains the list of user permissions that are needed to run the android
application.

Back to the program…

7. Now open the file HelloAndroid > src > android.examples.helloandroid > HelloAndroid.java
Add the boxed lines to the already present code.



 8. Save HelloAndroid.java.
    That’s it! Our Hello World program is ready!!
9. Right- click the project in Package Explorer and select
   Run As > Android Application.



 The Eclipse ADT plugin also adds the project to the Applications screen.


 But this is not very impressive. Let’s add some more functionality to the
project.
We will add a label, a text box and a button. When the user enters his name
in the text box and clicks the button, application should display “Hello
<username>!”
Here’s how:
 1.     Adding resources
  Open the file res > values > string.xml. There are two views available.
 The xml view and the UI based view called Resources
  I find the xml view easier. It looks like this.


Note that Android has added the name which we see on the title as
“app_name” automatically.

To this file add the highlighted lines.



These are the resources which we will be using in our application. Save
this file.

2. Understanding and changing the UI

Next, open the layout > main.xml file.



Notice that there 3 main sections here.
- Rectangle 1 encompasses all the views and layouts available for building the
UI.
- Rectangle 2 shows how the UI will look. We can drag and drop the components
from 1 to 2.
- Rectangle 3 shows the choices available to us to switch between the Graphical
Layout view and the xml view.

We can either add the components to the view shown or code them in the xml
file.

3. Adding components to the UI

Now drag a “TextView”, an “EditText”, a “Button” and another
“TextView”(outlined in Blue) on to the screen in rectangle 2.



TextView01, EditText01, Button01 and TextView02 are the ids of the TextView,
EditText and the Button respectively. The “@+id/”  part tells the IDE to put
these values in the R.java class in the class id.

4. Configuring properties

Each component has some configurable properties associated with it, which we
can change.
Right click on the TextView01, select Show In > Properties.
A properties window should be displayed at the bottom.



The text property of the TextView01 will have the value @+id/TextView01. We
want to change it to “Enter your name : ”.
For this we can enter the string directly in the value column against Text or
alternatively, since we have added this string in the resources, click the
ellipse outlined in red. A Resource Chooser window will pop up.



From this, select lbl_username and click OK.

The main.xml screen will display “Enter your name :” instead of
@+id/TextView01.
  • Now, for EditText01, clear the contents in the Value column of the Text property, since initially this should be empty. Also set the Layout width under the Misc properties to “match_parent”.
  • For Button01, set the Text property to the resource “btn_text”. Also against the On click property, enter “btn_OnClick”. This is the handler for the On Click event of the button.
  • For TextView02, clear the contents in the Value column of the Text property.
Once this is done the main.xml should look like this.



Now save main.xml, clean and build the project.

5.     Handling Events
Next, open the HelloAndroid.java file and change the code to the
following.



We can use the "Ctrl+Shift+O" shortcut to import the required packages and
remove the unnecessary ones.

The btn_OnClick method will handle the button click event of the Click
Me button.
It checks if the user has entered a name. If yes, then it displays “Hello
<username>”, else it displays “Please enter a name.”

That’s it! The application’s ready. Right-click on the project and select
Run As > Android Application.
Also, remember that it takes a long time for the emulator to start for the
first time.
So DO NOT close it after you run it for the first time. You can make
modifications to the project and Right-click on the project and select Run
As
> Android Application and the project will run in the open
Emulator!

 



Tuesday, February 8, 2011

Getting started with Android!

Introduction
Android, as everyone should be knowing by now, is Google’s mobile platform, which is overtly loved and appreciated by developers, geeks, critics as well as foodies (like me ;-)... since Android products are named after desserts). The global smartphone market is booming, and Google's Android platform was leading the pack during the fourth quarter 2010, according to a recent report issued on Monday by Canalys Smart Phone Analysis services.
Android is an operating system based on Linux with a Java programming interface. It provides development tools (compiler, debugger, device emulator, etc.) as well as its own virtual machine called the Dalvik Virtual Machine – DVM (analogous to Java Virtual Machine). Android is created by the Open Handset Alliance which is lead by Google.
Dalvik uses special bytecode. Therefore you cannot run standard Java bytecode on Android. Android provides a tool "dx" which allows to convert Java Class files into "dex" (Dalvik Executable) files.
Android applications are packed into an .apk (Android Package) file.
To simplify development Google provides the Android Development Tools (ADT) for Eclipse . The ADT automatically converts from class to dex files and creates the apk during deployment.
Android supports 2-D and 3-D graphics using the OpenGL libraries and supports data storage in a SQLite database.
Every Android application runs in its own process and under its own userid which is generated automatically by the Android system during deployment. Therefore the application is isolated from other running applications and a misbehaving application would not easily harm other Android applications.
Let’s get started!!!

Steps for installation and configuration of the device
1. If you have Eclipse 3.4 Ganymede or greater, proceed to step 2. Else you need to download Eclipse
     Classic from here.
2. Download the Android SDK starter package from here. I recommend that you download the .exe package
     (for Windows).
 If you downloaded a .zip or .tgz package (instead of the SDK installer), unpack it to a location on your  machine. By default, the SDK files are unpacked into a directory named android-sdk-<machine- platform>.
 If you downloaded the Windows installer (.exe file), run it and it will check whether the proper Java SE  Development Kit (JDK) is installed (installing it, if necessary). Then install the SDK Tools into a default  location.
 Make a note of the name and location of the SDK directory on your system—you will need to refer to 
 the SDK directory later, when setting up the ADT plugin for Eclipse.

3. Using Eclipse, install the Android Development Tools. Detailed steps for installing the ADT are given  
    below:
    If you have Eclipse 3.4 (Ganymede):
   a)      Start Eclipse.
   b)      Select Help > Software Updates.
   c)      In the dialog that appears, click Available Software tab.
   d)     Click Add Site.
   e)      In the dialog that appears, enter https://dl-ssl.google.com/android/eclipse in the Location field and
           click OK.
   f)      Back in the Available Software view, you will see the plugin listed with Developer Tools nested
           within it. Select the checkbox next to Developer Tools and click Install.
   g)     On the next installation window, all of the included tools should be checked. Click Next.
   h)     Read and accept the license agreement, then click Finish.
   i)      Once installation completes, restart Eclipse.

Alternatively, if you are using Eclipse 3.5 (Galileo) or Eclipse 3.6 (Helios):
   a)      Start Eclipse.
   b)      Select Help > New Software.
   c)      Click Add in the top right corner.
   d)      In the dialog that appears, enter ADT Plugin in the Name: field.
            Enter https://dl-ssl.google.com/android/eclipse in the Location: field. Click OK.
   e)      In the Available Software view, select the textbox next to Developer Tools and click Next.
   f)      Follow the steps g, h and i listed above.

4. Once the tools have been downloaded, next step is to Configure the ADT plugin.
   a)      Start Eclipse.
   b)      Select Windows > Preferences.
   c)      Select Android in the left hand side list.
   d)     Browse to the location of the Android SDK directory.

   e)      Click OK/ Apply.

5. Now select Window > Android SDK and AVD Manager.


Select Available Packages. Select the latest version of the SDK.


Click Install Selected, confirm license. Once installed, restart Eclipse.

6. Now we need to configure the device which will be used for emulation.
    For that, click the Device Manager button.
    
 
   Select Virtual Devices and click New…         

   

   Enter the following:


Click Create AVD.
To test if the setup has been done correctly, select your device and click Start. 
Have patience. The device takes a long time to start.

Thats it... Now we’re ready to build our first project!!!

Friday, January 14, 2011

Ways in which mobiles have and will change our world - part 2

In the previous post I talked about some of the significant ways in which mobiles have changed our world. In this post I will talk about a few more areas that will undergo phenomenal changes, thanks to the developments in the mobile technology.

6. Banking and payment

As mentioned earlier, mobiles have changed the way we do banking, and they will change this further.
E-banking is slowly changing to mobile banking. In the not very far future, all one will need to buy a gift for their loved ones, or to book their air tickets is a mobile.
You will say that payment can be done via internet too. Net banking and ‘Paypal’ do this.
No, that is not true. While we can use our credit card or Paypal on the internet, not everybody can. It is not possible to do money transfers 'natively' on the internet. You have to get a separate stand-alone account (like Paypal or a credit card) and only those who have a separate payment system, can do payments on the internet. That is not 'native' to the internet - its just an internet version of using your credit card on a phone call to the merchant, for booking an airline ticket. There are many people who do not use credit cards and Paypal, but there are many who use the mobile phone, right from the chai vala to the CEO of a Company.
On any mobile network if the provider decides to deploy the payment feature, we can make payments on one click - with NO separate payment system. 100% of mobile customers immediately will be able to handle the payment, on one click.
This trend is in the beginning stages. Banking regulations are yet not ready to handle mobile phone accounts, but this will happen.
Take ring tones for example - we can have ringing tones paid for on our mobile account, even if we have no credit card, no paypal, not even a bank account. The payments are taken care of by deducting the money from our 'prepaid' balance on the phone account. As I said the phone will become the wallet.

7. Health care

     The health care industry has experienced significant culture changes in the use of mobiles to have effective and reliable communication. The best feature is that a person is reachable even in emergencies. 
     There have been many applications. 
     Mobile technologies enable Telecare providers to decentralize and extend their reach to remote settings as well as to individual members with a comparatively smaller investment in technology infrastructure.
     A number of applications have been developed specifically for the health care industry using mobile phones such as reminders about appointments and medication, the use of a SIM card to hold medical data, peer support for patients, support for health professionals making a diagnosis, and data collection, contacting emergency services, etc.
     Many hospitals in the U.K. like the hospital of Cleveland, have adopted the iPhone since it provides efficient ways for the staff to keep in touch, to monitor patients, to access the hospital database, etc.
     Future applications may involve a plethora of mobile services like a patient in a remote area being sent a prescription via a mobile, or doctors having a video chat via mobiles to discuss the best possible way to treat a patient, pathological labs sending reports to patients via mobile phones, patients sending vital information like blood pressure and glucose level to their doctors via devices which are enabled to send messages to the patient’s doctor, etc.
     Industry visionaries, like mobile industry expert, Jeffrey Sachs at Columbia University in the US, predicts, “the cell phone is the single most transformative technology for development.”

     8. Advanced imaging
      
     Every new camera phone released is marketed as a replacement for cameras, that too a compact replacement. Smart phones (like Nokia’s N8, N86, C7, LG’s KC 910, Sony Ericisson’s Walkman W995 already come with a 8/ 8.1 MP camera, and Samsung’s M8910 Pixon which has a 12 MP camera – hold your breath – Carl Zeiss optics with an optical 3x zoom!!!) have already begun a trend to take over the traditional digital cameras. And these are just a few of them I mentioned above.
     As good as these features are, they aren't good enough to usurp a compact DV or still camera and the future will see a coming together of big names in the photography and mobile world as industry leaders in both fields realize that people don't want to carry a camera and a mobile device.
            
     So expect to see 12+ megapixels and 1080P capture, huge on-board storage and even full editing on the hoof with Photoshop and Premier among the software being used.
Mobiles are set to change the photography industry.
      
     9. Augmented reality

     Augmented reality is the future. What with the coming up of technologies like the Sixth sense, Google's 'Goggles', 'Wikitude' and 'Last Minute’s Nru', among others. But the AR technology has only just arrived into the marketplace.
     We can look forward to true location awareness, enabling clients to view their couriers’ progress in real-time, emergency services - showing the location of victims of crime or accident by their cellular signal and many other greatly useful applications to make our professional as well as personal lives more efficient and safer.
     Aside from advancement in AR apps, we can also expect a range of devices offering AR replacements for traditional methods of human input, ranging from virtualized keyboards and touchpads to eye-dialing your phone via a heads-up display while driving.
     AR may also be expected to fill the void between 2D projection and holographic projections, allowing users to conferencing, sharing information and tools and interacting via virtual controls and workspaces.
     Imagine pointing your camera phone at a giant 2D barcode on the ground and then what you see is a 3D rendering of a car!!! That’s the application of AR. 
     And that is exactly what Ford did with the launch of their new version of the KA. 2D barcodes were seen on streets of several large European cities. People could walk round the car and see it from all sides, yet it was virtual. There’s a high potential for the marketing giants in here.
     The application of AR technology will go beyond smartphones though. One can also expect to see augmented advertising hoardings and other interactive media in the future.

     10. Mobile cloud

     Let’s get to the hot topic of these days… the CLOUD. Along with the power and flexibility being populated in the small devices, we can expect to see a leap to cloud computing in the mobile market.
     With smaller, more powerful devices having the lion's share of their hard work done remotely, we can expect to have all the power that we need. Also, the de-centralized storage of documents, photographs and other data would enable users to work seamlessly with colleagues and even share devices without loss of data. In addition, the data would be secure ad available on-the-go to the users.
     Work in this field has already started with projects synchronizing a mobile’s contacts and media with an online repository dedicated to the user, a good example of which is Google Sync which synchronizes the calendar, contacts and gmail account from the user’s mobile.
     One can expect the mobile cloud to also see the distillation of mobile operating systems, leaving users with a quicker, more efficient experience when working on their devices.
The mobile cloud is already in use in certain applications such as Google's Gmail and Apple's MobileMe, but with more extensive usage the network infrastructure would have to be fast and stable enough to support the high amount of data transfer needed to make such a concept viable. The arrival of 4G is imminent, and with that we can expect a whole new array of higher specced hardware and a more robust network infrastructure.




These are just a few areas that the mobiles are going to affect. The possibilities are just what you can imagine.