Вы находитесь на странице: 1из 44

Report- Workshop on Android Application Development

Workshop on Android Application Development


(26th 27th May, 2011)
Held at C-DAC Knowledge Park, Bangalore

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

Report- Workshop on Android Application Development

About the workshop


The workshop was an initiative of C-DAC, Bangalore as a 2-day workshop on Android Application development, with an aim of giving detailed insight into the Open Source platform of Android, its architecture and its abilities for development of a wide variety of mobile applications. The primary focus of the workshop was on understanding the key concepts, best practices and insights of the Android architecture, and learning of some basic skills of Android Application development using Android SDK.

Schedule:
Duration of Workshop Timings Venue : : : 26th 27th May, 2011 09:30am 06:00pm CDAC Knowledge Park No.1, Old Madras Road Byyapanahalli, Bengaluru 560038 Sh. C V Ramdass, CDAC, Banglore Mr. Satish Patel, Texas Instruments Mr. Utkarsh Mankad, CDAC, Banglore Mr. Parimal Naigaonkar, CDAC, Banglore Mr. DSR Praveen Varma, CDAC, Hydrabad Detailed schedule of the workshop A CD (with sample code, setups and slides) Workshop Participation Certificate (at the end of the session)

Trainers

Materials Provided

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

Report- Workshop on Android Application Development DAY 1 26th May, 2011 Topic : Registration and issuing of ID Cards & goodies Welcome Address and Inauguration Ceremony 09:30am 09:45am

Timings

Topic Timing

: :

Current Mobile Platform trends and Activities 10:00am 10:30am Sh. C V Ramdass

Lead Speaker: Details :

The session was a briefing about: Current technological trends in the market Rising no of mobiles Everything on mobile and tabs Mobile platform most popular development platform currently Gartner Says 428 Million Mobile Communication Devices Sold Worldwide in First

Quarter 2011, a 19 Percent Increase Year-on-Year Available mobile platforms Android iPhone Java ME, etc Statistical data about the presence &

popularity of various mobile platforms

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

Report- Workshop on Android Application Development

Reason for selecting android as a platform 36 OEMs 215 Carriers 450000 Android Developers 310 devices in 112 Countries 400000 Android devices are activated daily A brief history of Android Android, Inc. was founded in Palo Alto, California, United States in October, 2003 by Google acquired Android Inc. in August, 2005 At Google, the team led by Rubin developed a mobile device platform powered by the On the November 5, 2007 the Open Handset Alliance, a consortium of several companies

Andy Rubin

Linux kernel unveiled itself

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

Report- Workshop on Android Application Development Topic Timing : : Porting of Android 10:45am 12:30pm Mr. Satish Patel, Texas Instruments

Lead Speaker: Details :

The session was regarding the porting of android over hardware. In this session the participants were over the following topics: Why is Android popular? Excellent GUI Freely available Faster application development Open Source Linux Kernel based Android Interface Definition Language (AIDL) Game Development Part of Open Handset Alliance (OHA) Why Android is Open Source? Fourth vector of PARTICIPATION in: o o o Content Applications Capabilities

General benefits of being open source o o o Faster Innovation Better solutions Faster feedback

Why do people participate in Open Source? Scratch an itch

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

Report- Workshop on Android Application Development Fame and Glory Great opportunity for fresher to show their skills Contribution of Open Source Programming languages o o Operating systems o o o Servers o o o Client software o o Mozilla Firefox web browser OpenOffice.org office suite Apache HTTP web server Tomcat web server web container Eclipse software development environment comprising an GNU Project a sufficient body of free software Linux operating system kernel based on Unix Symbian real-time mobile operating system PHP - Scripting language suited for the web Python - General purpose programming language

integrated development environment (IDE)

Benefits of Android Attractive Licensing (from Apache 2.0) o o The Android Open Source Project uses a few open source initiative The preferred license for the Android Open Source Project is the approved open source licenses for our software. Apache Software License, 2.0("Apache 2.0"), and the majority of the Android software is licensed with Apache 2.0. While the project will strive to adhere to the preferred license, there may be exceptions which will be handled on a case-by-case basis. For example, the Linux kernel patches are under the GPLv2 license with system exceptions, which can be found onkernel.org.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

Report- Workshop on Android Application Development

Open Source Licenses o o o GPL -Linux Kernel and modules, bluez BSD -Bionic Apache -almost everything else

Closed source Components o kernel drivers) o o o o cannot do) o o Open Source Large Ecosystems Committed roadmap Unlimited documentation Front end HW accel codec "Google apps" -Maps, Gmail, etc. libhgl.so - Qualcomm/ati opengl ES library libqcamera.so-Qualcomm camera library akmd-software to process and adjust compass/accelerometer events Qualcomm h264 codec front end (does some processing the DSP HTC RIL (radio interface) library and data files(this is glue between

the telephony layer in android and the AT/QMI control channels provided via GPL

Basic features of Android Application framework enabling reuse and replacement of components Dalvik virtual machine optimized for mobile devices Integrated browser based on the open source WebKit engine 7

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

Report- Workshop on Android Application Development Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the SQLite for structured data storage Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, GSM Telephony (hardware dependent) Bluetooth, EDGE, 3G, and WiFi (hardware dependent) Camera, GPS, compass, and accelerometer (hardware dependent) Rich development environment including a device emulator, tools for debugging,

OpenGL ES 1.0 specification (hardware acceleration optional)

AAC, AMR, JPG, PNG, GIF)

memory and performance profiling, and a plugin for the Eclipse IDE

How Android is different from Linux? Introduction

Android is an open source mobile device operating system developed by Google based on the Linux 2.6 kernel. The Linux kernel was chosen due to its proven driver model, existing drivers, memory and process management, networking support along with other core operating system services. In addition to the Linux kernel various libraries were added to the platform in order to support higher functionality. Many of these libraries originate from open source projects; however the Android team created their own C library, for example, in order to resolve licensing conflicts. They also developed their own Java runtime engine, optimized for the limited resources available on a mobile platform called the "Dalvik Virtual Machine." Lastly, the application framework was created in order to provide the system libraries in a concise manner to the end-user applications. Target Architecture

The Linux kernel supports many different target architectures. However only two are fully supported by Android at this time: x86 and ARM. The x86 architecture for Android is mainly targeted mainly at Mobile Internet Devices (MIDs) whereas the ARM platform is prevalent on mobile phones. These architectures are typically used for very different computer systems. The x86 platform is used for general purpose desktop/laptop/server computing whereas ARM is widely in use on mobile devices. Kernel Modifications

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

Report- Workshop on Android Application Development Android is based on the Linux, but does not use a standard Linux kernel. The kernel enhancements of Android include alarm driver, ashmem (Android shared memory driver), binder driver(InterProcess Communication Interface), power management, low memory killer, kernel debugger and logger. All these kernel enhancements have been contributed back to the open source community under the GNU Public License (GPL). Here is a summary of the most substantial components: alarm driver: provides timers to wake devices up from sleep ashmem: allows applications to share memory and manages the sharing in kernel levels. binder driver: facilitates inter-process communication since data can be shared by multiple applications through the use of shared memory. A service registered as an IPC service do not have to worry about different threads because binder will handle, monitor and manage them. Binder also takes care of synchronization between processes. power management: built on the top on standard Linux Power Management (PM) and take a more aggressive policy to manage and save power. BIONIC: Standard C Library

On most Linux distributions the GNU C library is used to provide the library routines specified by the ISO C standard for C language programs. Many developers view the GNU C library as being inappropriate for memory constrained platforms such as embedded systems. Furthermore, this library is licensed under the GNU Lesser Public License (LGPL) and therefore restricts licensing of derivative works. These concerns led the developers of Android to instead create their own C library called "Bionic". This library was designed to have fast execution paths, avoid edge cases and remain a simple implementation. It is composed partly from the BSD C library combined with Android original source code. This results in a combination of the BSD and Android licenses covering the entire library. Dalvik Virtual Machine

Many of the top cell phone manufacturers such as Nokia, Motorola and Samsung include a mobile optimized version of the Java virtual machine called Java 2, Micro Edition (J2ME). In contrast to these vendors Android uses their own Dalvik Virtual Machine. This development process is identical to the developer as a standard Java platform. Application developers write their program in Java and compile java class files. However, instead of the class files being run on a J2ME virtual machine, the code is translated after compilation into a "Dex file" that can be run on the Dalvik machine. A tool called dx will convert and repack the class files in a Java .jar file into a single dex file with several shared constant pools. This is used to reduce the duplicated arguments and make the dex file more compact. The virtual machine itself is optimized to perform well on mobile devices with a slow CPU, limited memory, no operating system swap space and most importantly limited battery power. These constraints can be quite tight. The Dalvik VM is optimized for low memory compared to other standard VMs due to the following changes: The VM was slimmed down to use less space. Dalvik has no just-in-time compiler

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

Report- Workshop on Android Application Development The constant pool has been modified to use only 32-bit indexes to simplify the interpreter. It uses its own bytecode, not Java bytecode. File System

Android uses the YAFFS flash file system, the first NAND optimized Linux flash file system. For mobile devices, hard disks are too large in size, too fragile and consume too much power to be useful. In contrast, flash memory provides fast read access time and better kinetic shock resistance than hard disks. There are fundamentally two different types of flash memory based on their construction technique: NOR and NAND. NOR is low density, offers slow writes and fast reads. NAND is low cost, high density and offers fast writes and slow reads. Embedded systems are increasingly using NAND flash for storage and NOR for code and execution.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

10

Report- Workshop on Android Application Development Comparison with other file system YAFFS (flash file system) and Ext3 (disk file system) have fundamental differences with each other, since the design principles of these two file system are based on the physical differences of each storage media. These differences can be summarized as follows: File accessibility: disk file systems are optimized to avoid disk seeks whenever possible due to high seeking cost; flash memory devices have no seek latency and can randomly access files. Block erasing: it is easy to erase a file on a disk; for flash devices it is quite time consuming therefore it should be done while the device is idle. Wear leveling techniques: only flash file systems have to deal with limited lifetime. Power Management

Android has its own Linux power extension, PowerManager. The core power was added to the Linux kernel in order to facilitate this functionality. This module provides low level drivers in order to control the peripherals supported by the Power Manager. These peripherals currently include: screen display and backlight, keyboard backlight and button backlight. Each peripheral's power is controlled through the use of WakeLocks. These locks are requested through the API whenever an application requires one of the managed peripherals to remain powered on. If no wake lock exists which "locks" the device, then it is powered off to conserve battery life. In the case of multiple power settings the transition is managed through the use of delays based on system activity. In addition to WakeLocks the PowerManager also monitors the battery life and status of the device. This service coordinates with the power circuitry charging in the battery and also powers down the system when the battery reaches a critical threshold.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

11

Report- Workshop on Android Application Development Topic Timing : : Android Internals 12:30pm 01:30pm Mr. Parimal Naigaonkar

Lead Speaker: Details :

The session was the briefing of following topics: Android Architecture

Android Internals Android is based on the Linux kernel Android is not Linux No native windowing system No glibc

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

12

Report- Workshop on Android Application Development Does not include full set of standard linux utilities Android relies on Linux version 2.6 for core system services such as The kernel also acts as an abstraction layer between the hardware and It comes up with several patch for kernel enhancement to support Hardware support seems) driver underneath ... Power Management-Wakelocks kernel patch Sensors-Manufacturer-provided libsensors.so Accelerometer Magnetic Field Orientation Gyroscope Light 13 GPS-Manufacturer-provided libgps.so Display-Std framebuffer driver (/dev/fb0) Lights-Manufacturer-provided liblights.so Backlight Keyboard Buttons Battery Notifications Attention Keymaps and Keyboards Std input event (/dev/event0) Audio-Manufacturer-provided libaudio.so(could use ALSA underneath Camera-Manufacturer-provided libcamera.so(could use V4L2 kernel Bluetooth BlueZ through D-BUS IPC (to avoid GPL contamination it

security, memory management, process management, network stack, and driver model the rest of the software stack. Android

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

Report- Workshop on Android Application Development <RIL version>.so Wifi wpa_supplicant Directory tree of android Pressure Temperature Proximity Radio Layer Interface-Manufacturer-provided libril-<companyname>-

Why kernel for android? Great memory and process management Great permissions based security model Proven driver model Support for shared libraries Its already open source Further modifications Low memory killer Kernel debugger Logger Android debug bridge (ADB) Hardware specific driver

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

14

Report- Workshop on Android Application Development Kernel Enhancements: Binder Driver to facilitate inter-process communication High performance through shared memory Per-process thread pool for processing requests Reference counting and mapping of object references across processes Synchronous calls between processes.

Power management Built on top of standard Linux power management More aggressive power manager Components make requests to keep power via wake locks Supports different types of wake locks android.os.PowerManager

Android Security Model Each Android application runs inside its own Linux Process. Additionally, each Application has its own sandbox file system with its own set of preferences and its own database. Other applications cannot access any of its data, unless it is explicitly shared.

Layer Interaction App -> Runtime Service -> Lib App -> Runtime Service -> Native Service -> Lib App -> Runtime Service -> Native Daemon -> Lib

It will depend on the type of app and type of native library which method works best.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

15

Report- Workshop on Android Application Development Topic Timing : : Hello Android 02:15pm 03:45pm Mr. Utkarsh Mankad

Lead Speaker: Details :

The session was the briefing of following topics: Setting up of Android Application Development Environment

Basic System requirements Supported Operating Systems Windows XP (32-bit), Vista (32-or 64-bit), or Windows 7 (32-or 64-bit) Mac OS X 10.5.8 or later (x86 only) Linux (tested on Ubuntu Linux, Lucid Lynx)

Supported Development Environments Eclipse IDE JDK 5 or JDK 6 (JRE alone is not sufficient) Android Development Tools plug-in(recommended) Not compatible with Gnu Compiler for Java (gcj)

Other development environments or IDEs Apache Ant 1.8 or later

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

16

Report- Workshop on Android Application Development Installing ADT Plug-in on Eclipse IDE Open the Eclipse IDE, click on the tab "Workbench", this will take we to the work bench. Go to Help -> Install New Software Now in the work with tab, click on Add button, and then follow the instructions given in

the ADT (Android Development Tool) installation link -The ADT URL is -follow the instructions in the installation. Then click on next, and then let the installation finish. Once the IDE has restarted, go to Window -> Preferences. Then click on the "Android" Then, again go to Windows -> Android Device and AVD manager, then click on tab on the screen coming on the left hand side Available packages tab, in the list coming on the left hand side of the screen, in the main window, a list of currently available Android version and other extensions for application development will be shown Setting up Android Virtual Device (AVD)

An Android Virtual Device (AVD) is an emulator configuration that lets us model an actual device by defining hardware and software options to be emulated by the Android Emulator o Features of AVD A hardware profile: Defines the hardware features of the virtual

device. For example, we can define whether the device has a camera, whether it uses a physical QWERTY keyboard or a dialing pad, how much memory it has, A mapping to a system image: we can define what version of the Other options: we can specify the emulator skin we want to use Android platform will run on the virtual device. with the AVD, which lets we control the screen dimensions, appearance, and so on. We can also specify the emulated SD card to use with the AVD. stored in this area. A dedicated storage area on our development machine: the device's user data (installed applications, settings, and so on) and emulated SD card are

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

17

Report- Workshop on Android Application Development

What can we do with AVD Emulate SD card Emulate GPS, accelerometer, camera, video recorder etc Run internet Load applications inside the emulated SD card. Enter real time data Use QWERTY key board Multiple language support. Use native emulator apps like google maps etc. Perform real time debugging Customize settings and themes.

Debugging android applications

The main components that comprise a typical Android debugging environment are: Adb - adb acts as a middleman between a device and our development system. It provides

various device management capabilities, including moving and syncing files to the emulator, running a UNIX shell on the device or emulator, and providing a general means to communicate with connected emulators and devices. Dalvik Debug Monitor Server - DDMS is a graphical program that communicates with our devices through adb. DDMS can capture screenshots, gather thread and stack information, spoof incoming calls and SMS messages, and has many other features. Device or Android Virtual Device our application must run in a device or in an AVD so that it can be debugged.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

18

Report- Workshop on Android Application Development o Android Debugger Bridge (ADB)

Android Debug Bridge (adb) is a versatile tool lets us manage the state of an emulator instance or Android-powered device. It is a client-server program that includes three components: A client, which runs on our development machine. We can invoke a

client from a shell by issuing an adb command. Other Android tools such as the ADT plug-in and DDMS also create adb clients. A server, which runs as a background process on our development machine. The server manages communication between the client and the adb daemon running on an emulator or device. device instance. o Dalvik Debugger Monitor Server (DDMS) A daemon, which runs as a background process on each emulator or

Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS), which provides port-forwarding services, screen capture on the device, thread and heap information on the device, logcat, process, and radio state information, incoming call and SMS spoofing, location data spoofing, and more. Viewing heap usage for a process DDMS allows us to view how much heap memory a process is using. This information is useful in tracking heap usage at a certain point of time during the execution of our application. To view heap usage for a process: information for. process. Click the Update Heap button to enable heap information for the In the Devices tab, select the process that we want to see the heap

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

19

Report- Workshop on Android Application Development In the Heap tab, click Cause GC to invoke garbage collection,

which enables the collection of heap data. When the operation completes, we will see a group of object types and the memory that has been allocated for each type. We can click Cause GC again to refresh the data. Click on an object type in the list to see a bar graph that shows the number of objects allocated for a particular memory size in bytes. Tracking memory allocation of objects DDMS provides a feature to track objects that are being allocated to memory and to see which classes and threads are allocating the objects. This allows us to track, in real time, where objects are being allocated when we perform certain actions in our application. To track memory allocation of objects: In the Devices tab, select the process that we want to enable In the Allocation Tracker tab, click the Start Tracking button to

allocation tracking for. tracked. Click Get Allocations to see a list of objects that have been allocated since we clicked on the Start Tracking button. we can click on Get Allocations again to append to the list new objects that that have been allocated. Tracking button. Click on a specific row in the list to see more detailed information such as the method and line number of the code that allocated the object. To stop tracking or to clear the data and start over, click the Stop begin allocation tracking. At this point, anything we do in our application will be

Working with an emulator or device's file system

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

20

Report- Workshop on Android Application Development DDMS provides a File Explorer tab that allows us to view, copy, and delete files on the device. This feature is useful in examining files that are created by our application or if we want to transfer files to and from the device. To work with an emulator or device's file system: system for. To copy a file from the device, locate the file in the File Explorer To copy a file to the device, click the Push file button on the File and click the Pull file button. Explorer tab. Examining thread information The Threads tab in DDMS shows we the currently running threads for a selected process. In the Devices tab, select the process that we want to examine the threads for. Click the Update Threads button. In the Threads tab, we can view the thread information for the selected process. Starting method profiling Method profiling is a means to track certain metrics about a method, such as number of calls, execution time, and time spent executing the method. Before we start method profiling in DDMS, be aware of the following restrictions: To start method profiling: profiling for. profile. Click the Stop Method Profiling button. DDMS stops profiling our application and opens Trace view with the method profiling information that was Click the Start Method Profiling button. Interact with our application to start the methods that we want to On the Devices tab, select the process that we want to enable method In the Devices tab, select the emulator that we want to view the file

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

21

Report- Workshop on Android Application Development collected between the time we clicked on Start Method Profiling and Stop Method Profiling. Using LogCat LogCat is integrated into DDMS, and outputs the messages that we print out using the Log class along with other system messages such as stack traces when exceptions are thrown. When we have set up our logging, we can use the LogCat feature of DDMS to filter certain messages with the following buttons: Verbose Debug Info Warn Error

We can also setup our own custom filter to specify more details such as filtering messages with the log tags or with the process id that generated the log message. The add filter, edit filter, and delete filter buttons let we manage our custom filters. Changing network state, speed, and latency Voice -unregistered, home, roaming, searching, denied Data -unregistered, home, roaming, searching, denied Speed -Full, GSM, HSCSD, GPRS, EDGE, UMTS, HSDPA Latency -GPRS, EDGE, UMTS Spoofing calls or SMS text messages Voice -Enter a number in the Incoming number field and click Call to send a simulated call to the emulator or phone. Click the Hang up button to terminate the call. SMS -Enter a number in the Incoming number field and a message in the Message: field and click the Send button to send the message. Setting the location of the phone

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

22

Report- Workshop on Android Application Development Manual -set the location by manually specifying decimal or sexagesimal longitude and latitude values. GPX -GPS eXchange file KML -Keyhole Markup Language file

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

23

Report- Workshop on Android Application Development Hello Android Application Create a new project by file -> New Project -> Android Project. Enter the details o o o o o Project Name HelloWorldBuild Target Android 2.2 (API 8) Application Name Hello Android Package name cdac.android.helloworld Activity name HelloWorldActivity

Click on finish, and wait for the project to be created. Then build your project. Then click on the play icon in the taskbar on the top, or right click on the project folder in Select the AVD corresponding to the build target, and then wait for the emulator to load.

the workspace, and then select android application

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

24

Report- Workshop on Android Application Development Topic Timing : : Activities 04:00pm 06:00pm Mr. Utkarsh Mankad

Lead Speaker: Details :

The session was the briefing of following topics: File Structure of Android project src - an assets folder

This src folder, contains the actual source code res and assets folder

The Resource aka res folder, contains all the resource files which are divided into generally 5 folders drawable hdpi drawable ldpi drawable mdpi layout values

Apart from all other files are added to the assets folder like java projects. The gen folder

The gen folder contains the file R.java. This file is auto generated R.Java contains set of unique precompiled IDs assigned to every resource in the res folder. The default.properties file

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

25

Report- Workshop on Android Application Development This file generally contains the information regarding the version of Android used to make the application. But, in order to specify or change the build environment or parameters well modify this file.

Android Manifest File

The manifest lets you define the structure and metadata of your application, its components, and its requirements. Activity tag To describe any new activity in the application Application, intent-filter tag Android Permissions (uses-application tag) - The Android permissions are the set of

hardware/software permissions to be taken by the current application. Android Activity

An Activity is an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. The very first step in developing an Android application is making an Activity. Your application must have at least one Activity. Importance of an Activity

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI. Creating an Activity

To create an activity, you must create a subclass of Activity (or an existing subclass of it). In your subclass, you need to implement the most important callback methods are: onCreate() The system calls this when creating your activity.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

26

Report- Workshop on Android Application Development Most importantly, this is where you must call setContentView() to define the layout for the activity's user interface. onPause() This is usually where we should commit any changes that should be persisted beyond the current user session (because the user might not come back).

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

27

Report- Workshop on Android Application Development Activity Lifecycle

The entire lifetime of an activity happens between the call to onCreate() and the call to onDestroy(). Your activity should perform setup of "global" state (such as defining layout) in onCreate(), and release all remaining resources in onDestroy(). For example, if your activity has a thread running in the background to download data from the network, it might create that thread in onCreate() and then stop the thread in onDestroy(). The visible lifetime of an activity happens between the call to onStart() and the call to onStop(). During this time, the user can see the activity on-screen and interact with it. For example, onStop() is called when a new activity starts and this one is no longer visible. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver in onStart() to monitor changes that impact your UI, and unregister it in onStop() when the user can no longer see what you are displaying. The system might call onStart() and onStop() multiple times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user. The foreground lifetime of an activity happens between the call to onResume() and the call to onPause(). During this time, the activity is in front of all other activities on screen and has user input focus. An activity can frequently transition in and out of the foregroundfor example, onPause() is called when the device goes to sleep or when a dialog appears. Because this state can transition often, the code in these two methods should be fairly lightweight in order to avoid slow transitions that make the user wait.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

28

Report- Workshop on Android Application Development DAY 2 27th May, 2011 Topic Timing : : Basic UI Elements in Android and Event Handling 09:00am 11:30am Mr. DSR Praveen Varma

Lead Speaker: Details :

The session was a briefing about: Basic UI Elements UI Widgets o o o o Layouts o o o o o Frame Layout Linear Layout Relative Layout Tabular Layout Absolute Layout TextView EditText CheckBox RadioGroup etc

The Web View and the Web Kit Browser The Android browser is based on WebKit, the same engine that powers Apple's Safari Web Android uses the WebView widget to host browsers pages Applications using the WebView component must request INTERNET permission.

browser.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

29

Report- Workshop on Android Application Development

Menu Creating Menus

Creating menu resource requires creating an XML file inside the project's res/menu/ directory and build the menu with the following elements: <menu>

Defines a Menu, which is a container for menu items. A <menu> element must be the root node for the file and can hold one or more <item> and <group> elements. <item>

Creates a MenuItem, which represents a single item in a menu. This element may contain a nested <menu> element in order to create a submenu. <group>

An optional, invisible container for <item> elements. It allows you to categorize menu items so they share properties such as active state and visibility Inflating Menus

From the application code, inflate a menu resource (convert the XML resource into a programmable object) using MenuInflater.inflate() during the onCreateOptionsMenu() callback method. Responding to user actions

When the user selects a menu item from the Options Menu, the system calls your activity's onOptionsItemSelected() method.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

30

Report- Workshop on Android Application Development Dialogs A dialog is usually a small window that appears in front of the current Activity. The underlying Activity loses focus and the dialog accepts all user interaction. Dialogs are normally used for notifications that should interrupt the user and to perform

short tasks that directly relate to the application in progress (such as a progress bar or a login prompt). Types of Dialog Alert Dialog

A dialog that can manage zero, one, two, or three buttons, and/or a list of selectable items that can include checkboxes or radio buttons. The AlertDialog is capable of constructing most dialog user interfaces and is the suggested dialog type. Progress Dialog

A dialog that displays a progress wheel or progress bar. Because it's an extension of the AlertDialog, it also supports buttons. Creating and dismissing Dialog o o o o o Creating a Dialog onCreateDialog(int) To change any properties of the dialog each time it is opened onPrepareDialog(int, Dialog) Showing a Dialog showDialog(int) Closing a Dialog dismiss() dismissDialog(int)

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

31

Report- Workshop on Android Application Development Toast

A toast notification is a message that pops up on the surface of the window. It only fills the amount of space required for the message and the user's The notification automatically fades in and out, and does not accept A toast can be created and displayed from an Activity or Service. If a toast

current activity remains visible and interactive. interaction events. notification is created from a Service, it appears in front of the Activity currently in focus. Using resources General project structure

Resource directories supported

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

32

Report- Workshop on Android Application Development Configuration Qualifiers by dashes. o o o R Class drawable-en-rUS-land/ The qualifiers must be in the order listed in Configuration qualifier table. Wrong: drawable-hdpi-port/ Correct: drawable-port-hdpi/ Values are case-insensitive. Only one value for each qualifier type is supported. One can specify multiple qualifiers for a single set of resources, separated

All resource IDs are defined in the project's R class, which the aapt tool automatically generates. A resource ID is composed of: The resource type: Each resource is grouped into a "type," such as string, The resource name, which is either: the filename, excluding the extension;

drawable or layout. or the value in XML android:name attribute. Accessing resources o o In Code: Using a static integer from a sub-class of R class. In XML: Using @<res-type>/<id> access the resource form R class.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

33

Report- Workshop on Android Application Development Topic Timing : : Intents, Services and Broadcast receivers, Databases and Content providers 11:20am 01:30pm Mr. Utkarsh Mankad

Lead Speaker: Details :

The session was a briefing about: Intents

Intent in Android Intents are used as a message-passing mechanism that works both within application, and between applications. Intents in Android are used to fulfill the intentions to An Activity or Service be started to perform an action, usually with (or on) a Broadcast that an event (or action) has occurred Explicitly start a particular Service or Activity particular piece of data

Types of Intents explicitly defined Implicit Where an action be performed on a piece of data is requested Explicit Where the Activity or the Service class to be loaded is

Intent Filters

Intent Filters are used to register Activities, Services, and Broadcast Receivers as being capable of performing an action on a particular kind of data. Using Intent Filters, application components announce that they can respond to action requests from any application installed on the device.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

34

Report- Workshop on Android Application Development Android Notifications

Notification message is shown on the top of the screen, to alert users that events have occurred that may require attention. The NotificationManager class is responsible for handling the Notifications-Its capability are: window Create new status bar icons Display additional information (and launch an Intent) in the extended status bar Flash the lights/LEDs Vibrate the phone Sound audible alerts (ringtones, Media Store audio)

Android Service

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Additionally, a component can bind to a service to interact with it and even perform Interprocess Communication (IPC). Importance and use

A facility for the application to tell the system about something it wants to be doing in the background (even when the user is not directly interacting with the application). Creating a service Create a class that extends the Serviceclass Add this new Service to the manifest by adding a new service tag within Override the onStartCommand and onCreate. Set the return type of the START_STICKY START_NOT_STICKY

the application node. onStartCommand method from one of these to set the service behavior

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

35

Report- Workshop on Android Application Development START_REDELIVER_INTENT To start a Service, call startService; we can either use an action to

implicitly start a Service with the appropriate Intent Receiver registered, or we can explicitly specify the Service using its class. If the Service requires permissions that our application does not have, the call to startService will throw a SecurityException. Service to stop. Service Life Cycle To stop a Service use stopService, passing an Intent that defines the

Mode 1 - Context.startService() If someone calls Context.startService() then the system will retrieve the

service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Mode 2 - Context.bindService() On calling Context.bindService() to obtain a persistent connection to a

service creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinderobject that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's Ibinder Android Interface Definition Language (AIDL)

It allows us to define the programming interface that both the client and service agree upon in order to communicate with each other using Interprocess Communication (IPC).When you build each application that contains the .aidl file, the Android SDK tools generate an IBinderinterface based on the .aidl file and save it in the project's gen/ directory. The service must implement the IBinderinterface as appropriate. To create a bounded service using AIDL, follow these steps:

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

36

Report- Workshop on Android Application Development

signatures.

Create the .aidlfile This file defines the programming interface with method Implement the interface The Android SDK tools generate an interface in the

Java programming language, based on our .aidl file. This interface has an inner abstract class named Stub that extends Binder and implements methods from our AIDL interface. We must extend the Stub class and implement the methods. Expose the interface to clients Implement a Service and override onBind() to Broadcast Recievers return our implementation of the Stub class.

A broadcast receiver is a class which extends BroadcastReceiver class and which is registered as a receiver in an Android Application via the AndroidManifest.xml (or via code). This class will be able to receive intents via the sendBroadcast() method. Broadcast receiver is a component that responds to system-wide broadcast announcements. Broadcast receivers are implemented in order to monitor and respond any changes in the intents which are registered with it. SQLite Databases

Android provides full support for SQLite databases. Any databases we create will be accessible by name to any class in the application, but not outside the application. To create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which we can execute a SQLite command to create tables in the database. getWritableDatabase() and getReadableDatabase() - to write and read from database. Their return type is SQLiteDatabase class that provides methods for database operations. SQLiteDatabasequery() methods to execute queries, these methods takes various parameters, for various quires.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

37

Report- Workshop on Android Application Development Cursor - It is the return type of any SQLite query and the mechanism with which we can navigate results from a database query and read rows and columns. Content Providers

Content providers are interfaces to store and retrieve data and make it accessible to all applications. They're the only way to share data across applications Using content providers

We should expose a public static CONTENT_URI property that returns the full URI of this provider. We will use the URI matcher for this. Then expose queries and transactions on our ContentProvider by implementing the delete, insert, update, and query methods. Using content resolvers

The ContentResolver is the interface that is used to obtain the underlying data using its various abstract methods.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

38

Report- Workshop on Android Application Development Topic Timing : : GPS Capabilities 02:15pm 03:30pm Mr. DSR Praveen Varma

Lead Speaker: Details :

The session was all about using android.location package and Google maps external library. Following topics were covered in the session: Location Services

The central component of location framework is the LocationManager system service, which provides APIs to determine location and bearing of the underlying device. Request an instance of LocationManager from the system by calling getSystemService(Context.LOCATION_SERVICE). Once the application has a LocationManager, it can do three things: Query for the list of all LocationProviders for the last known user location. Register/unregister for periodic updates of the user's current location from a Register/unregister for a given Intent to be fired if the device comes within a

location provider (specified either by criteria or name). given proximity (specified by radius in meters) of a given lat/long.

Requesting user permissions To receive location updates from NETWORK_PROVIDER

<manifest ... > <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> ... </manifest> To receive location updates from GPS_PROVIDER <manifest ... > <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> ... </manifest>

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

39

Report- Workshop on Android Application Development Finding Providers Based on Requirement Accuracy (fine or coarse) Power use (low, medium, high) Cost To return values for altitude, speed and bearing

Criteria

If more than one LocationProvider match the criteria, one with the greatest accuracy is returned. If no Location Providers meet the requirements, criteria are loosened in the following order until a provider is found: Power use Accuracy Ability to return bearing, speed, and altitude

Using the Geocoder Geocoding lets you translate between street addresses and longitude/latitude The Geocoder class provides access to following geocoding functions: Forward Geocoding Finds the latitude and longitude of an address. Reverse Geocoding Finds the street address for a given latitude and longitude map coordinates

Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault());

Creating Map-Based Activities MapView is the actual view of map(control). MapActivity is the base class extended to create a new Activity that can include

a MapView.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

40

Report- Workshop on Android Application Development Overlay is the class used to annotate maps. Using Overlays, a Canvas can be MapController is used to control the map, allowing to set the center location Configuring and Using Map Views The MapView class is a View that displays the actual map; it includes several The type of map can be chosen as follows o o o mapView.setSatellite(true); mapView.setStreetView(true); mapView.setTraffic(true); Display the standard map zoom controls options for deciding how the map is displayed.

drawn onto any number of layers that are displayed on top of a Map View. and zoom levels.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

41

Report- Workshop on Android Application Development Topic Timing : : Android Native Development 03:30pm 04:30pm Mr. Parimal Naigaonkar

Lead Speaker: Details :

The session was about learning how to use Native Programming in android applications. Following topics were covered: Java Native Interface (JNI)

JNI defines naming and coding convention so that Java VM can find and call native code. JNI is built into JVM to provide access to OS I/O and others. The following examples illustrate when you need to use Java native methods: The standard Java class library does not support the platform-dependent features You already have a library written in another language, and wish to make it You want to implement a small portion of time-critical code in a lower-level needed by the application. accessible to Java code through the JNI. language such as assembly. By programming through the JNI, you can use native methods to: Create, inspect, and update Java objects (including arrays and strings). Call Java methods. Catch and throw exceptions. Load classes and obtain class information. Perform runtime type checking.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

42

Report- Workshop on Android Application Development

Native Development Kit (NDK) Whats in NDK

Tools to build and compile your native code for the device architecture (such as ARM) A set of native system headers that will be supported for the future releases of Android platform (libc, libm, libz,liblog, JNI headers, some C++ headers, and OpenGL) A way to package your library into the APK file so you can distribute your application easily (some) documentation, sample code and examples It provides a set of system headers for stable native APIs that are guaranteed to be supported in all later releases of the platform: libc(C library) headers libm(math library) headers JNI interface headers libz(Zlibcompression) headers liblog(Android logging) header OpenGL ES 1.1 and OpenGL ES 2.0 (3D graphics libraries) headers libjnigraphics(Pixel buffer access) header (for Android 2.2 and above). A Minimal set of headers for C++ support OpenSLES native audio libraries Android native application APIS

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

43

Report- Workshop on Android Application Development Why NDK?

NDK allows you to develop parts of your Android application in C/C++. You cannot develop native-only apps in NDKyour app is still subject to security sandboxing. Main motivation for native code is performance. Using NDK

The Android framework provides two ways to use native code: Write your application using the Android framework and use JNI to access the APIs

provided by the Android NDK. This technique allows you to take advantage of the convenience of the Android framework, but still allows you to write native code when necessary. You can install applications that use native code through the JNI on devices that run Android 1.5 or later. Write a native activity, which allows you to implement the lifecycle callbacks in native code. The Android SDK provides the Native Activity class, which is a convenience class that notifies your native code of any activity lifecycle callbacks (onCreate(), onPause(), onResume(), etc). You can implement the callbacks in your native code to handle these events when they occur. Applications that use native activities must be run on Android 2.3 (API Level 9) or later. You cannot access features such as Services and Content Providers natively, so if you want to use them or any other framework API, you can still write JNI code to do so.

Copy Right 2011. Applied AI Group. CDAC, Pune. All Rights Reserved

44

Вам также может понравиться