Tuesday, November 30, 2010

Android CLI Tools

Hello everyone, this is my second article on Android Application Development. This time I will be introducing you to the command line utilities that comes packaged with the Android SDK. All these utilities are extensively used to create an Android Application. When using an IDE(Integrated Development Environment) like Eclipse, the developer never realises about the existense of these utilities because IDE's provide abstraction between developer and implementation of the process to create an application package. We all being an open source enthusiasts and Linux users, we should know how to build an application from command line, and to know exactly what is going on behind the scenes. I will be introducing you to some tools that comes along with Android SDK. This will give you a better understanding of the process involved in creating an android application. This knowledge will also help you in debugging the application.

These are the tools that are packaged with the Android SDK :


In this folder there are many tools available but we will be looking at the below tools, as they are used most often. The tools we will be dealing with are:

  • adb

  • android

  • ddms

  • emulator

  • mksdcard

  • sqlite3

  • traceview

We will be looking each tool in detail in the following sections.

  • Adb:

      • adb stands for “Android Debug Bridge”. Its main functionality is to manage the state of the emulator instance which is running or the android based phone which is connected to the system.

      • Adb is based on a client – server mechanism where in “client” is the Android Emulator instance or the Android device connected and “server” is your development machine. Server communicates with the client through a daemon process which runs in the background of your development system.

      • Issuing commands to the android instances using adb:

        • adb server is running on your development machine and now we need to attach this server to a client. Here we can have multiple clients, like 2 emulator instances running simulteneously, 1 USB device plugged along the instances, etc. Therefore we need to find the number of clients connected to development machine. This is done by running the following command,

          $ adb devices

      • Now, when we know the number of clients, we can run a command directed specifically towards a particular client/instance. This can be done by running the following command:

                $ adb -s command

                $ adb -s emulator-5554 shell

            • serial-number: The name of the device that you see after issuing

              adb devices command under List of Devices column.

            • command can be any adb command like :

              • install <.apk file> : Installs an android application on the device

              • shell : presents you the adb client's console

              • logcat: displays all the log information on the system console

                To see all the other commands that you can use with adb can be found here: http://goo.gl/pQ0s

  • Android:

      • This is a very important tool in terms of developing an android application. It lets you do 3 things:

        • To create and delete Android Virtual Deveices (AVD / emulators).

          • When a new AVD/emulator instance is created, “android” creates a dedicated folder for your AVD with a mapping to the system image, userdata image, sd-card image and some other files required by AVD.

            Note: Each AVD does not contain a separate system image but it contains a mapping to it. Config.ini file maps the avd to system image based on the target of device(android-7(Eclair 2.1), android-8(Froyo 2.2)).

          • To create an AVD, there are some things we have to decide like the target of the device, this can be found by issuing this command:

$ android list targets

this shows the android targets supported by your development system.

          • Now once you have decided the target with which you want to create an AVD, we issue the following command to create an AVD:

$ android create avd -n myandy_2.2 -t 3

-n : Signifies the name of the AVD you want to specify.

-t : Signifies the “id” of the target with which the AVD needs to be created

Figure-4 Figure-5 Figure-6

Figure-4 shows you all the targets I have on my system and Figure-5 & 6 shows you the prompts that are asked when you create a new AVD for its hardware profile.

$ android list avd

Similarly if you want to delete an AVD then you can issue this command:

$ android delete avd -n myandy_2.2

        • To create and update android projects

          • Eclipse IDE creates a new Android Project in a very intuitive way but internally what it does is issue the following command:

$ android create project --target 3 \

--name HelloWorld \

--path ./Workspace/MyAndroidAppProject \

--activity HelloWorldActivity \

--package home.saket

Figure-7 Figure-8

        • Updating the android platform that you have on your development machine with the latest android releases, add-ons, etc. This can be done by launching the AVD Manager directly from the command line by issuing :

$ android

Figure-9

  • DDMS:

        It stands for “Dalvik Debug Monitoring Service”. It is the debugger tool which is shipped along with the android SDK. It provides a way to debug our application running on the device remotely on our development machine. It can be launched from the command line by issuing the following command:

        Note: It is assumed that you have the android tools directory set in your $PATH

$ ddms

Figure-10

This launches the debugger automatically attached to the running emulator instances.

In this debugger tool, you can view all the emulators attached as well as the processes running respective to the emulator instances on the left pane. On the right pane you can see some tabs for monitoring some emulator properties. We can see the “memory usage” of each of the applications running on the emulator, we can also see the CPU load, etc from the SysInfo tab. Similarly, we can also test an application by calling the emulator instance. It is done by entering the number in the “Incoming Number” field under Emulator Control tab.

Memory Usage Figure-11 Incoming Number Figure-12

In the same way we can also see the heap status of the device by causing Garbage collection of the device. It is done by following the below steps:

  • Select a process from the left pane

  • Under VM Heap, if it is written that “No Heap updates are available for this client” then we need to select Show Heap Updates button on top of left pane and then click the “Cause GC” button in VM Heap tab.

  • We will be able to see the heap update status showing the available memory in the device along with some extra information about the heap.

  • Emulator:

This tool is used to launch and control the emulator instance. An AVD created by the “Android” utility can be launched or stopped using the emulator utility. An AVD can be launched by issuing the follwing command:

$ emulator -avd

Ex: $ emulator -avd myandy_2.2

We can use emulator utility to control various hardware simulations of the emulator instance, like networking, media, etc. There are many options available to play around with the emulator utility. These options are also referred to as “startup options”.

General Syntax of using emulator utility:

emulator -avd

Example 1: When you run emulator instance by using

emulator -avd

OR

emulator @

you will not be able to see the logging information on the system terminal. Therefore, by starting the emulator instance with the startup option “-logcat” we will be able to see the initial logging that happens during the boot up of android OS.

Example 2: We can also open up a root shell on the emulator instance by using the foolwoing command:

emulator -avd -shell

Example 3: This startup option disables the animation of the android logo during boot.

emulator -avd -no-boot-anim

Networking in Emulator:

When an emulator instance is powered up, it always runs behind a virtual router/firewall and hence isolated from the development environment. All the address spaces that are handled by emulator instances are in the range of “10.0.2.0 – 10.0.2.99”

Note: To access the developement machine's localhost, it is by default set to 10.0.2.2.

Once the emulator instance is running, we can connect to the instance using a simple telnet connection.

$ telnet localhost

Ex: $ telnet localhost 5554

Type help on the android console and you will be presented with some commands as shown in the below figure.

Figure-13


Similarly, there are plenty of options available for the emulator, you can find all the options at http://goo.gl/Mmqh

  • Mksdcard:

          This tool lets you create an sdcard disk image which you can load it into the emulator. The file system created will be of the format FAT32.

          To create and load an sdcard file into an emlator instance we issue the following commands:

$ mksdcard -l

Ex: $mksdcard -l S 512M saket.img

$emulator @myandy_2.2 -sdcard saket.img

                      Figure-14

  • Sqlite3:

          This command is used to enter the sqlite database system. Using this command you can create, modify the databases present inside your emulator instance.

          To enter into the database of your android device, you need to enter the following commands:

$ emulator @myandy_2.2 -shell

# sqlite3

sqlite3> .help

Generally when you have a database based android application, your application database is stored in “/data/data//databases”.

          You can perform DDL, DML statements in exactly the same way as in SQL.

sqlite3> create table employee(

emp_id int,

emp_name varchar(20)

);

sqlite3> .tables

employee

  • Traceview:

          This tool is used to profile the application. To be able to use this utility, there are some requirements that your application should have. The application code has to have “Debug.startTracingMethod(String tracename)” method call at the beginning and “Debug.stopTracingMethod()” call at the end of the method to stop tracing. This method stores the tracing information onto an SDCard and hence your emulator instance should have an SDCard attached. The tracing methods writes a file at “/sdcard/.trace” and hence we need to give permissions to ou application to be able to write a file on SDCard. The permission is given in “AndroidManifest” as

          android.permission.WRITE_EXTERNAL_STORAGE” />”

          When application is run on the emulator, we need to pull the trace file from the emulator instance and feed it to “traceview” utility. This is done in the following way:

$ adb pull /sdcard/HelloWorld.trace /tmp

$ traceview /tmp/HelloWorld.trace

          Now, you will be presented with a traceview window as shown in Figure-16 below,

This GUI traceview is divided into 2 sections:

  • Timeline Section

  • Profile Section

Timeline Section shows you the execution time of each Thread in corresponding rows.

Profile Section shows you all the time that is spent by CPU inside a method with some statistics included in separate columns.

Some other tools that are used internally are

  • dx: This is used to convert a .class file to .dex file.

  • Monkey: This tool is used for stress testing of an android application. It issues random events on the application like touch, gesture, click events to test an android application.

    Lets run monkey on email application which comes packaged when we create a new emulator instance,

$ emulator @andy_2.2

$ adb shell monkey -p com.android.email -v 500

Monkey is actually a android device console tool, it is passed the application package name(com.android.email) and number of tests(500) that it has to test for application.

I hope you would have liked the article and this knowledge share would be helpful in your quest with Android. I will be back with some other interesting information on Android Application Development in the coming editions.Furthermore, we will discuss building advanced application on Android and for Android.



Sunday, July 25, 2010

Android Application Development

What is Android?

Android is a collection of softwares for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.

Android Features:

1. Application framework enabling reuse and replacement of components
2. Dalvik virtual machine optimized for mobile devices
3. Integrated browser based on the open source WebKit engine
4. Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)
5. SQLite for structured data storage
6. Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
7. GSM Telephony (hardware dependent)
8. Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
9. Camera, GPS, compass, and accelerometer (hardware dependent)
10. Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE

Android Architecture:



Android applications are written in the Java programming language. The compiled Java code — along with any data and resource files required by the application is bundled into an Android package, an archive file marked by an .apk suffix.

Sample Application:

The sample application that I am going to use is a Simple Interest Calculator that I had built when I started with Android Application Development. I intend to explain beginners about android application development using this application.

Environment Setup:

Android Application Development starts with setting up environment for android application by following the steps mentioned in the android developer site.

The steps below provide an overview of how to get started with the Android SDK.

1. Prepare your development computer

You may need to install the JDK (version 5 or 6 required) and Eclipse (version 3.4 or 3.5, needed only if you want develop using the ADT Plugin).

2. Download and install the SDK starter package

Select a starter package for android sdk and download it to your development computer. To install the SDK, simply unpack the starter package to a safe location and then add the location to your PATH(if windows).

3. Install the ADT Plugin for Eclipse

If you are developing in Eclipse, set up a remote update site at https://dl-ssl.google.com/android/eclipse/ under Help -> Install New Software -> Add. Install the Android Development Tools (ADT) Plugin, restart Eclipse, and set the "Android" preferences in Eclipse to point to the SDK install location.

Note: If the above mentioned link doesn't work then just replace https with http.

4. Add Android platforms and other components to your SDK

Use the Android SDK and AVD Manager, included in the SDK starter package, to add one or more Android platforms (for example, Android 2.0 or Android 2.2) and other components to your SDK. Preferably just download the latest of the lot. You can also download the documentation for the version of Android you are downloading.

To launch the Android SDK and AVD Manager on Windows, execute SDK Setup.exe, at the root of the SDK directory. On Linux, execute the android tool in the /tools/ folder which would be " /tools/ sudo sh android "

Once you setup thee environment for android application development you can start by creating a sample project by creating an Android Project using Eclipse IDE as shown in below figure:


The fields that are shown here have a specific meaning attached to it.
1. Project Name specifies the name of the project that a user can give.
2. Just check one of the android libraries from the list presented to you by the Eclipse IDE.
3. Application Name specifies the title that is shown when you run your application.
4. Package name field has to be at least 2 levels deep.
5. Activity name specifies the name of your class that is going to be created and this class will extend the Activity class from android library. We will cover activity class later in the tutorial.

When the new android project is created you get the following folder structure as shown below:




Lets now discuss the folder structure because I feel it would help you in segregating your resources for the application in a proper way.

1. src :
This folder holds all the java classes that you create.

2. res:
This folder stands for Resource, it holds all your images, layout files, and string value xml.

3. drawable:
There are 3 folders for storing images based on the resolution sizes of the screens of mobile phones.

4. layout:
This folder consists of a single xml file initially defining the layout configurations.

5. values:
This folder holds a xml file named strings.xml file. This file maps values of ID's with string values. This topic will be discussed later in the tutorial.

6. AndroidManifest.xml:
This is the main configuration file for the whole of android application. It defines the way your application will be launched, the number of activities present in your application, the permissions that your application has, etc, etc..

7. default.properties:
This file is generally used for localization purposes.

Now, lets start the tutorial with the main.xml file which configures the layout of our application.

Layout terms that will be used are very similar to Java SWING components.

1. LinearLayout:
A layout that arranges its children in a single row or column. It has some attributes like orientation which specifies whether the layout will be single row or column.

2. Button:
It specifies a single button.

3. EditText:
This corresponds to a editable textbox field where a user can enter data.

4. TextView:
This tag corresponds to a Label field.

Android offers 2 kinds of layout design, XML layout, UI layout which is provided by ADT. I prefer XML layout because I am used to it and UI layout development is a bit jerky as of now and needs a lot of improvement.

Using the above tags I have written the layout of this demo application in main.xml which you can refer from http://code.google.com/p/simpleinterestcalculator/

Now lets get to the java part of android application development.
Here I have created only one java class for performing an operation. As the application becomes complex we can have multiple java classes performing operations.

1. Activity:
Activity in android terms is nothing but a screen window. We extend our class with Activity because we need a single screen window for having a UI for the application and shown to the user. When you want to perform different actions or have multiple screens application then you need to have separate java classes extending Activity class for each of the screen windows.

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

When you create a new android project, these are the 3 lines of code that will be automatically generated by the Eclipse IDE for you.

1. onCreate() method is the method that gets invoked when your application starts.
2. It calls the super onCreate() method to set initial parameters of the screen window which is referred as Activity class.
3. setContentView(R.layout.main) initializes the screen layout with main.xml.

We have the layout set for our application. Now our job is to find a way to refer to the UI elements on java side. To accomplish this we have a method named findViewById(), this gets the UI element based on the ID that we assign to each UI component while designing the layout in main.xml.

Ex: messageBox = (Button)findViewById(R.id.box);

You can refer to the code from http://code.google.com/p/simpleinterestcalculator/. In this example :

1. We get the reference of Calculate button because we perform action only on click of the button.

2. We assign an OnClickListener() to the button which catches the event of CLICK of the button and makes the user override the onClick() method of the listener.

3. We perform the basic validations of the fields of the EditText elements for NULL value.

4. We use the wrapper class of Double to convert the string values to their actual Double values.

5. If any error occurs then we show the user a Toast message which is nothing but a display of a pop up message telling the user about the error.

6. If all the validations holds good then calculate the simple interest from the formula and display it in a Alert dialog box showing the calculated interest. Syntax that needs to be used to show the AlertDialog is:

AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getContext());
// set the message to display
alertbox.setMessage("Simple Interest = "+si.toString());
// add a neutral button to the alert box and assign a click list alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1) {
// the button was clicked
Toast.makeText(getApplicationContext(), "Thank You !!!!", Toast.LENGTH_LONG).show();
}
});

// show it
alertbox.show();

I have also created a screen cast of this application which you can refer and get to know how the application works.

This was a very basic overview of Android Application Development using a basic example but "There is a lot more to Android That Meets The Eye", for more information on android and demo applications you can refer to the following links:

References:


Groups:


Tuesday, June 29, 2010

Some Of My Android Demo Applications

1. My First Android Demo Application



2. Date & Time



3. Basic Twitter UI




4. My Blog Seen From Android



5. Touch Me Not!!!



6. Simple Interest Calculator