Você está na página 1de 68

A REPORT

ON

Android Application Development


BY

Akash Khaitan

08DDCS547

AT

Sevya It. Pvt. Ltd., Hyderabad

An Internship Program-III Station of

Faculty of Science and Technology


The ICFAI University, Dehradun

June 2012

A REPORT

ON

Android Application Development


BY

Akash Khaitan

08DDCS547

Prepared in Partial Fulfillment of the IP 401 Internship ProgramIII Course AT

Sevya It. Pvt. Ltd., Hyderabad An Internship Program-III Station of

Faculty of Science and Technology


The ICFAI University, Dehradun

June 2012

Acknowledgement

We would like to express our gratitude to Prof. R.C.Ramola center head, FACULTY OF SCIENCE AND TECHNOLOGY, Prof. T.K Mandal IP coordinator, FACULTY OF SCIENCE AND TECHNOLOGY and towards all the faculty members for allowing us in taking the industrial training according to the our curriculum and to bring about industrial awareness .This training at Sevya It. Pvt. Ltd., gave me an opportunity to realize the ways the IT industries work and the problem it faces during the course.

I also thank Mr. Srikant Reddy Modugula (Director), Mrs. Sivaparvathi Avula (HR), Mr. Narasayya Donepudi (Director), M.r Harsh Gupta, Mr. Aditya Kumar, Mr Kumar Raja Donthamsetti and Mr. Vineet Agarwal of Sevya It. Pvt. Ltd. who tried their best to provide us all the facilities needed by our team and cooperated in all possible ways.

I thank our faculty in charge Dr. Gouri Sankhar Brahma who has helped us all throughout with his guidance and also helped us in the completion of this report.

Faculty of Science and Technology


The ICFAI University, Dehradun

Station: Duration:

Sevya It. Pvt. Ltd. 5 Months 14 Days 15th June, 2012 Android Application Development

Center: Hyderabad Date of Start: 2nd Jan, 2012

Date of Submission: Title of the project:

ID No./Name(s)/Discipline(s)/of the student(s) : 08DDCS547 Akash Khaitan CS

Name(s) and Designation(s) of the expert(s): Mr Srikant Modugula(Director), Mr Narasayya Donepudi (Director), Mrs. Sivaparvathi Avula (HR), Mr Kumar Raja Donthamsetti (Mobile Application Developer), Mr Vineet Agarwal(Mobile Application Developer) Name of the IP Faculty: Key Words: Project Areas: Abstract: Dr. Gouri Sankhar Brahma Mobile Application Development, Android Application Development Training This project deals with Android Application Development which includes application developed using Android SDK and Java Platform. It also include in brief about the game development and web development for android

Signature of Student Date

Signature of IP Faculty Date

Table of Contents
1 2 Introduction ............................................................................................................................. 1 Architecture............................................................................................................................. 2 2.1 2.2 Linux Kernel .................................................................................................................... 3 Libraries ........................................................................................................................... 3 Surface Manager ....................................................................................................... 3 Media Libraries ......................................................................................................... 3 SQLite ....................................................................................................................... 3 System C library........................................................................................................ 3 LibWebCore.............................................................................................................. 4 SGL ........................................................................................................................... 4 3D libraries................................................................................................................ 4 FreeType ................................................................................................................... 4

2.2.1 2.2.2 2.2.3 2.2.4 2.2.5 2.2.6 2.2.7 2.2.8 2.3 2.4 2.5 3

Android Runtime .............................................................................................................. 4 Application Framework.................................................................................................... 5 Applications ..................................................................................................................... 5

Activity.................................................................................................................................... 6 3.1 3.2 3.3 3.4 3.5 Activity Lifecycle............................................................................................................. 6 Context ............................................................................................................................. 7 Intents ............................................................................................................................... 8 Data passing between Activities ...................................................................................... 8 Implicit Intent ................................................................................................................... 9

4 5

Services ................................................................................................................................. 10 User Interface ........................................................................................................................ 11 5.1 View Group .................................................................................................................... 12 Layouts.................................................................................................................... 12

5.1.1 5.2

Views.............................................................................................................................. 15 TextView................................................................................................................. 15 EditText................................................................................................................... 15 Spinner .................................................................................................................... 15 Button & Image Button........................................................................................... 16

5.2.1 5.2.2 5.2.3 5.2.4

5.2.5 5.2.6 5.2.7 5.2.8 6

ImageView .............................................................................................................. 17 CheckBox................................................................................................................ 17 RadioButton ............................................................................................................ 17 WebView ................................................................................................................ 18

Menus.................................................................................................................................... 20 6.1 6.2 6.3 6.4 Defining a Menu in XML............................................................................................... 20 Defining Activity class ................................................................................................... 20 Creating Menu ................................................................................................................ 21 Handling Menu Click Events ......................................................................................... 21

Navigation ............................................................................................................................. 22 7.1 Tabs ................................................................................................................................ 22 Create Separate Activity ......................................................................................... 23 Create layout for activity......................................................................................... 23 Create a layout with Tabhost as the root element ................................................... 23 Add tabs using the activity class which extends TabActivity................................. 24 On Tab Changed ..................................................................................................... 25

7.1.1 7.1.2 7.1.3 7.1.4 7.1.5 7.2

Lists ................................................................................................................................ 26 Simple Lists............................................................................................................. 26 Custom Lists ........................................................................................................... 27 Custom Adapter ...................................................................................................... 28 List Activity ............................................................................................................ 29

7.2.1 7.2.2 7.2.3 7.2.4 7.3 8

Listener ........................................................................................................................... 30

Notification ........................................................................................................................... 31 8.1 Toast Notification........................................................................................................... 32 Simple Toast Notification ....................................................................................... 32 Custom Toast Notification ...................................................................................... 32

8.1.1 8.1.2 8.2

Status Bar Notifications ................................................................................................. 34 Simple Status Bar Notification ............................................................................... 35 Custom Status Bar Notification .............................................................................. 36

8.2.1 8.2.2 8.3

Dialogs ........................................................................................................................... 37 Simple Dialogs ........................................................................................................ 37

8.3.1

8.3.2 9

Custom Dialogs....................................................................................................... 39

Storage Based Application Development ............................................................................. 42 9.1 Shared Preferences ......................................................................................................... 44 Writting to SharedPreference.................................................................................. 44 Retrieving Shared preferences ................................................................................ 45

9.1.1 9.1.2 9.2

Internal Storage .............................................................................................................. 45 Writing to Internal Storage ..................................................................................... 45 Retrieving from Internal Storage ............................................................................ 46

9.2.1 9.2.2 9.3

External Storage ............................................................................................................. 47 Writing to External Storage .................................................................................... 47 Retrieving from External Storage ........................................................................... 47

9.3.1 9.3.2 9.4

SQLite Database............................................................................................................. 48 Get Database ........................................................................................................... 49 Inserting Data .......................................................................................................... 49 Deleting Data .......................................................................................................... 49 Updating Data ......................................................................................................... 50 Retrieving Data ....................................................................................................... 50

9.4.1 9.4.2 9.4.3 9.4.4 9.4.5 10

Multimedia ............................................................................................................................ 51 10.1 10.1.1 10.1.2 10.2 10.3 10.3.1 Audio .......................................................................................................................... 51 To Record................................................................................................................ 51 To Play .................................................................................................................... 51 Tone Generator ........................................................................................................... 52 Video........................................................................................................................... 52 To Play Video ......................................................................................................... 52

11

Mobile Web Apps ................................................................................................................. 53 11.1 11.2 11.3 11.4 11.5 Linking with native Libraries ..................................................................................... 53 UI Look and feel like native application .................................................................... 53 Navigation like native application .............................................................................. 54 Advantages ................................................................................................................. 54 Disadvantages ............................................................................................................. 54

12

Game Development............................................................................................................... 55

12.1 12.2 12.3 12.3.1 12.3.2 12.3.3

Accelerometer Based Games ...................................................................................... 55 Getting Accelerometer Readings ................................................................................ 55 Building Game ............................................................................................................ 56 Main Activity class ................................................................................................. 56 Create Custom View ............................................................................................... 57 Creating Stage Screens............................................................................................ 57

Conclusion ...................................................................................................................................... ix References ........................................................................................................................................x Glossary .......................................................................................................................................... xi

Android Application Development

1 Introduction
Android is a software stack 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. This report describes some of the below topics in details Architecture Activity Services User Interface Menus Navigation Notifications Data Storage Techniques Multimedia Game Development Web Application Development
Figure 1 : Android

Introduction

Android Application Development

2 Architecture
Android Architecture contains the following layers: Linux Kernel Libraries Android Run time Application Framework Applications The below Figure 2 shows the complete android architecture

Figure 2 : Android Architecture

Architecture

Android Application Development

2.1

Linux Kernel

Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as abstraction layer between the hardware and the rest of the software stack.

2.2 Libraries
Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. Some of the core libraries are listed below: 2.2.1 Surface Manager

Manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications 2.2.2 Media Libraries

Based on Packet Video's Open CORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG 2.2.3 SQLite

A powerful and lightweight relational database engine available to all applications 2.2.4 System C library

A BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices

Architecture

Android Application Development 2.2.5 LibWebCore

A modern web browser engine which powers both the Android browser and an embeddable web view 2.2.6 SGL

The underlying 2D graphics engine 2.2.7 3D libraries

An implementation based on Open GL ES 1.0 APIs; the libraries use either Hardware 3D acceleration (where available) or the included, highly optimized 3D software 14rasterizer 2.2.8 FreeType

Bitmap and vector font rendering

2.3 Android Runtime


Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language. Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool. The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.

Architecture

Android Application Development

2.4 Application Framework


By providing an open development platform, Android offers developers the ability to build extremely rich and innovative applications. Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, and add notifications to the status bar, and much, much more. Developers have full access to the same framework APIs used by the core applications. The Application architecture is designed to simplify the reuse of components. Underlying all applications is a set of services and systems, including: A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data A Resource Manager, providing access to non-code resources such as localized strings, Graphics, and layout files A Notification Manager that enables all applications to display custom alerts in the status bar An Activity Manager that manages the lifecycle of applications and provides a common Navigation back stack

2.5 Applications
Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language.

Architecture

Android Application Development

3 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. Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows. An application usually consists of multiple activities that are loosely bound to each other. Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching the application for the first time. Each activity can then start another activity in order to perform different actions. Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and takes user focus. The back stack abides to the basic "last in, first out" stack mechanism, so, when the user is done with the current activity and presses the Back button, it is popped from the stack (and destroyed) and the previous activity resumes.

3.1 Activity Lifecycle


When an activity is stopped because a new activity starts, it is notified of this change in state through the activity's lifecycle callback methods. There are several callback methods that an activity might receive, due to a change in its statewhether the system is creating it, stopping it, resuming it, or destroying itand each callback provides you the opportunity to perform specific work that's appropriate to that state change. When the activity resumes, you can reacquire the necessary resources and resume actions that were interrupted. These state transitions are all part of the activity lifecycle.

Activity

Android Application Development

Figure 3 : Activity Lifecycle

3.2 Context
Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system.

Activity

Android Application Development


It allows access to application-specific resources and classes, as well as up-calls for

application-level operations such as launching activities, broadcasting and receiving intents, etc.

3.3 Intents
Intents are

asynchronous message which allows Android components to request

functionality from other components of the Android system. For example an Activity can send Intents to the Android system which starts another Activity.
Intent can also contain data. This data can be used by the receiving component. Android supports explicit and implicit Intents.

3.4 Data passing between Activities


Intent can also carry small amounts of data to be used by the activity that is started. The component which creates the Intent can add data to it via the overloaded putExtra()

method.
Extras are key/value pairs; the key is always a String. As value you can use the primitive

data types (int, float,..), String, Bundle, Serializable.


Below illustration shows, how intent carries data
Intent intent = new Intent(this, ActivityTwo.class); intent.putExtra("Value1", "This is Value 1 "); intent.putExtra("Value2", "This is value 2 "); startActivity(intent);

Activity

Android Application Development Receiving Extra data in sub activitys onCreate() method
Intent intent=getIntent(); String receivedString=intent.getExtras().getString(Value1)

3.5 Implicit Intent


Do not specify the Java class which should be called. They specify the action which should be performed and optionally an URI which should be used for this action. For example, if you want to call a number automatically you could have used this intent:
Intent in=new Intent(Intent.ACTION_CALL,Uri.parse(tel:9999999999)); startActivity(in); If you use this it requires adding the following p ermission to the manifest file: <uses-permission android:name="android.permission.CALL_PHONE"> Another example to launch an intent to open the browser and navigate to a certain URL: Intent in=new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")); startActivity(in); If you use this it requires adding the following p ermission to the manifest file: <uses-permission android:name="android.permission.INTERNET"/>

Activity

Android Application Development

4 Services

A service can run in the background to perform work even while the user is in a different application

A service can allow other components to bind to it, in order to interact with it and perform intercrosses communication

A service runs in the main thread of the application that hosts it, by default

Figure 4 : S ervice Lifecycle

Services

10

Android Application Development

5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as

controls). All UI controls, including the layout classes, are derived from View.

View Groups View Groups are extensions of the View class that can contain multiple

child Views. Extend the ViewGroup class to create compound controls made up of interconnected child Views. The ViewGroup class is also extended to provide the layout managers that help you lay out controls within your Activities.

Figure 5 : View Group

User Interface

11

Android Application Development

5.1 View Group


5.1.1 Layouts

Layout managers (more generally just called layouts) are extensions of the ViewGroup class used to positioning child controls for your UI. Layouts organize views, such as grouping together a button and label or a group of them.

Layouts and Views Relationship

Figure 6 : Layout & View Relationship

The Android SDK includes some simple layouts to construct UI. The following list

includes layout classes available:

User Interface

12

Android Application Development 5.1.1.1 FrameLayout The Frame Layout simply pins each child view to the top left corner. Adding multiple children stacks each new child on top of the one before, with each new View obscuring the last.

Figure 7 : Frame Layout

5.1.1.2 LinearLayout A Linear Layout aligns each child View in either a vertical or a horizontal line. A vertical layout has a column of Views, while a horizontal layout has a row of Views. An important property for LinearLayout is orientation and valid options are vertical or horizontal.

Figure 8 : Linear Layout

User Interface

13

Android Application Development 5.1.1.3 RelativeLayout The Relative Layout lets you define the positions of each child View relative to the others and to the screen boundaries.

Figure 9 : Relative layout

5.1.1.4 TableLayout The Table Layout lets you lay out Views using a grid of rows and columns.

Figure 10 : Table Layout

User Interface

14

Android Application Development

5.2 Views
Android supplies a toolbox of standard Views to help you create simple interfaces. By using these controls (and modifying or extending them as necessary), you can simplify your development and provide consistency between applications. The following list highlights some of the more familiar toolbox controls: 5.2.1 TextView

A standard read-only text label. It supports multi-line display, string formatting, and automatic word wrapping.

5.2.2

EditText

It accepts multiline entry, word-wrapping, and hint text. Collecting Different Types of Input: By default, any text contents within an EditText control is displayed as plain text. The default software keyboard is used, for inputting plain text.

5.2.3

Spinner

A composite control that displays a Text View and an associated List View that lets you select an item from a list to display in the textbox. Its made from a Text View displaying the current selection, combined with a button that displays a selection dialog when pressed.

User Interface

15

Android Application Development

Figure 11 : S pinner

5.2.4

Button & Image Button

A standard push-button. Android SDK includes two simple button controls for use within your layouts: Button (android.widget.Button) and ImageButton (android.widget.ImageButton). These controls function in a similar way but the difference between the controls is mostly visual; the Button control has a text label, whereas the ImageButton uses an image drawable resource instead.

Figure 12 : Button

Figure 13 : Image Button

User Interface

16

Android Application Development 5.2.5 ImageView

A View which can load images from various sources (such as resources) and display to the user. It can and provides various display options such as scaling.

Figure 14 : ImageView

5.2.6

CheckBox

A two-state button represented by a checked or unchecked box. 5.2.7 RadioButton

A two-state grouped button. A group of these presents the user with a number of binary options of which only one can be enabled at a time.

Working with RadioGroup Controls: A RadioGroup control is simply a container for RadioButton controls, but it does have some useful properties. For example, you can have horizontal and vertical radio button groups. This is set using the the android:orientation attribute

User Interface

17

Android Application Development

Figure 15 : Radio Button

5.2.8

WebView

A View that displays web pages. This class is used roll own web browser or simply display some online content within your Activity.

Figure 16 : User Created Content

Figure 17 : Web Content

To add a WebView to your Application, simply include the <WebView> element in your

activity layout. For example : User Interface 18

Android Application Development


<?xml version="1.0" encoding="utf-8"?> <WebView xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" />

To load a web page in the WebView, use loadUrl(). For example:


WebView webView = (WebView) findViewById(R.id.webview); webView.loadUrl("http://www.google.com");

You can also load from an HTML string:


String summary = "<html><body>You scored <b>192</b> points.</body></html>"; webview.loadData(summary, "text/html", null);

In order for your Activity to access the Internet and load web pages in a WebView, you

must add the INTERNET permissions to your Android Manifest file:


<manifest ... > <uses-permission android:name="android.permission.INTERNET" /> ... </manifest>

User Interface

19

Android Application Development

6 Menus
Menus are a common user interface component in many types of applications. To provide a familiar and consistent user experience, one should use the Menu APIs to present user actions and other options in your activities. Objective: The below described application plays songs when the play is clicked from menu and pauses when the pause button is clicked from menu

6.1 Defining a Menu in XML


Here the menu.xml is defined
Figure 18 : Menu

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/play" android:icon="@android:drawable/ic_media_play" android:title="Play"></item> <item android:id="@+id/stop" android:icon="@android:drawable/ic_media_pause" android:title="Stop"></item> </menu>

6.2 Defining Activity class


As per the objective, the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity { /** Called when the activity is first created. */ MediaPlayer mp; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mp = new MediaPlayer(); try { mp.setDataSource(Environment.getExternalStorageDirectory().getAbsoluteP ath()+"/Music"+"/Flute Art.mp3"); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) {

Menus

20

Android Application Development


e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }

6.3 Creating Menu


The below code of lines inflates the menu.xml to the menu of the activity. Thus a menu is successfully created.
public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; }

6.4 Handling Menu Click Events


When the user selects an item from the options menu, the system calls activity's onOptionsItemSelected() method. The method passes the MenuItem selected which can be identified by calling getItemId(). See the code given below
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.play: { try { mp.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mp.start(); break; } case R.id.stop: mp.pause(); break; } return true; }

Menus

21

Android Application Development

7 Navigation
This section covers components for interactive navigation for user. The components to be discussed in the chapter are:

Tabs lists

7.1 Tabs
Use of tabs is essential navigation feature supported by android where users of the application can view different activity in the same page, in different tabs A tabhost consists of a tab widget for the tabs and frame layout for the activity space. Objective: To create a tab view consisting of

three tabs with a different activity on each tab. Steps Involved


Figure 19 : Tabs

Create three separate Activities Create three different layouts for activities Create a layout with Tabhost as the root element Add tabs using the activity class which extends TabActivity

Navigation

22

Android Application Development 7.1.1 Create Separate Activity

Here one activity is illustrated, create other two


package com.soulastral.tab; import android.app.Activity; import android.os.Bundle; public class Email extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.email); } }

7.1.2

Create layout for activity

Create a layout for above activity which is to be set in set content view of the activity.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Email Activity"/> </LinearLayout>

7.1.3

Create a layout with Tabhost as the root element

<?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout

Navigation

23

Android Application Development


android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp" /> </LinearLayout> </TabHost>

7.1.4

Add tabs using the activity class which extends TabActivity

package com.soulastral.tab; import android.R.anim; import android.R.drawable; import android.app.Activity; import android.app.TabActivity; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener;

public class Tab extends TabActivity implements OnTabChangeListener{ /** Called when the activity is first created. */

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TabHost tabHost=getTabHost(); TabHost.TabSpec spec;

Navigation

24

Android Application Development


Intent intent; Resources res = getResources(); intent = new Intent().setClass(this, Email.class); spec = tabHost.newTabSpec("email").setIndicator("Email",res.getDrawable(drawable.sym _action_email)).setContent(intent); tabHost.addTab(spec); intent = new Intent().setClass(this, Call.class); spec = tabHost.newTabSpec("call").setIndicator("Call", res.getDrawable(drawable.sym_action_call)) .setContent(intent); tabHost.addTab(spec); intent = new Intent().setClass(this,Chat.class); spec = tabHost.newTabSpec("chat").setIndicator("Chat", res.getDrawable(drawable.sym_action_chat)) .setContent(intent); tabHost.addTab(spec); tabHost.setOnTabChangedListener(this);

} }

7.1.5

On Tab Changed

Listener when tab is switched


@Override public void onTabChanged(String tabId) { // TODO Auto-generated method stub }

Navigation

25

Android Application Development

7.2 Lists
The list in android displays the items in the list format and clicking events on the list item is managed by the programmer. The section describes:

Simple Lists(Default List): Contains a default row layout and takes Array adapter Custom Lists : Row layout and custom adapter is defined by the programmer

In order to completely understand list one must understand the concept of adapters.

Adapters: Adapter binds the data from array to the row layout of the list and runs up to the length of the array implicitly and thus populates the list.

7.2.1

Simple Lists

Objective : To create a simple list


Extend listActivity setListAdapter with normal Arrayadapter<String> and


simple_list_item_1 layout
Figure 20 : S imple List

package com.soulastral.simplelist; import android.app.Activity; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter;

Navigation

26

Android Application Development


import android.widget.ListView; import android.widget.Toast; public class SimpleListActivity extends ListActivity { /** Called when the activity is first created. */ static final String[] ACTIVITY_CHOICES = new String[] { "Action 1", "Action 2", "Action 3" }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ListView li=getListView(); setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ACTIVITY_CHOICES)); } }

7.2.2

Custom Lists

Objective: To create custom row layout, custom adapter and custom list with an arrow image 7.2.2.1 Custom Row
Figure 21 : Custom List

Create a row .xml as shown below


<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >

Navigation

27

Android Application Development


<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/textbox" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAppearance="@android:style/TextAppearance.Medium" android:gravity="center_vertical" android:layout_gravity="center_vertical" android:layout_weight="0.8"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@android:drawable/ic_media_play"/> </LinearLayout>> </LinearLayout>

7.2.3

Custom Adapter

A custom adapter is to be created for the purpose which would bind the array data to the row and run up to the length of the array implicitly
package com.soulastral.customlist; import java.security.Provider.Service; import import import import import import android.content.Context; android.view.LayoutInflater; android.view.View; android.view.ViewGroup; android.widget.ArrayAdapter; android.widget.TextView;

public class CustomAdapter extends ArrayAdapter<String> { Context context; String []objects; int row; public CustomAdapter(Context context, int textViewResourceId, String[] objects) { super(context, textViewResourceId, objects); this.context=context; this.objects=objects; row=textViewResourceId; // TODO Auto-generated constructor stub } @Override public View getView(int position, View convertView, ViewGroup parent) {

Navigation

28

Android Application Development


// TODO Auto-generated method stub if(convertView==null) { LayoutInflater lf=(LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE); convertView=lf.inflate(R.layout.row, parent, false); } TextView tv=(TextView)convertView.findViewById(R.id.textbox); tv.setText(objects[position]); return convertView; } }

7.2.4

List Activity

The main list activity which would control the total function
package com.soulastral.customlist; import android.app.Activity; import android.app.ListActivity; import android.os.Bundle; import android.widget.ListView; public class CustomListActivity extends ListActivity { static final String[] ACTIVITY_CHOICES = new String[] { "Action 1", "Action 2", "Action 3" }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ListView li=getListView(); CustomAdapter ca=new CustomAdapter(getApplicationContext(), R.layout.row,ACTIVITY_CHOICES ); li.setAdapter(ca); } }

Navigation

29

Android Application Development

7.3 Listener
To react to selections in the list set an OnItemClickListener to your ListView.
li.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(getApplicationContext(), "Click ListItem Number " + position, Toast.LENGTH_LONG) .show(); } });

Navigation

30

Android Application Development

8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs in application. Some events require the user to respond and others do not. For example:

When an event such as saving a file is complete, a small message should appear to confirm that the save was successful.

If the application is running in the background and needs the user's attention, the application should create a notification that allows the user to respond at his or her convenience.

If the application is performing work that the user must wait for (such as loading a file), the application should show a hovering progress wheel or bar.

Each of these notification tasks can be achieved using a different technique:

A Toast Notification, for brief messages that come from the background. A Status Bar Notification, for persistent reminders that come from the background and request the user's response.

A Dialog Notification, for Activity-related notifications.

This document summarizes each of these techniques for notifying the user and includes links to full documentation.

Notification

31

Android Application Development

8.1 Toast Notification


8.1.1 Simple Toast Notification

The default toast notification the code for which is given below

Figure 22 : S imple Toast Notification

package com.soulastral.toastnotification; import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.widget.Toast; public class ToastNotificationActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

Toast toast= Toast.makeText(getApplicationContext(), "Here is the Toast Notification",Toast.LENGTH_LONG ); toast.show(); toast.setGravity(Gravity.CENTER_HORIZONTA L, 0, 0); } }

8.1.2

Custom Toast Notification

Steps Involved

Notification

32

Android Application Development


For a custom toast Notification user must first create a layout for the Toast Populate the layout with the desired Values setView for Toast object

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas. android.com/apk/res/android" android:id="@+id/cuslay" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="10dp" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#FFF" /> </LinearLayout>
Figure 23 : Custom Toast Notification

package com.soulastral.customtoastnotification; import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class CustomToastNotificationActivity extends Activity { /** Called when the activity is first created. */ @Override

Notification

33

Android Application Development


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

LayoutInflater inflater=getLayoutInflater(); View layout=inflater.inflate(R.layout.customtoast, (ViewGroup)findViewById(R.id.cuslay)); ImageView image = (ImageView) layout.findViewById(R.id.image); image.setImageResource(R.drawable.ic_launcher); TextView text = (TextView) layout.findViewById(R.id.text); text.setText("Hello! This is a custom toast!"); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); } }

8.2 Status Bar Notifications


A status bar notification should be used for any case in which a background service needs to alert the user about an event that requires a response. A background service should never launch an activity on its own in order to receive user interaction. The service should instead create a status bar notification that will launch the activity when selected by the user.
Figure 24 : S imple S tatusBar Notification

Notification

34

Android Application Development 8.2.1 Simple Status Bar Notification

The below code creates a simple status bar notification as shown in figure
package com.soulastral.statusbarnotification; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; public class StatusbarNotificationActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String ns = Context.NOTIFICATION_SERVICE; NotificationManager getSystemService(ns); mNotificationManager = (NotificationManager)

int icon = R.drawable.ic_launcher; CharSequence tickerText = "Hello"; long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);

Context context = getApplicationContext(); CharSequence contentTitle = "My notification"; CharSequence contentText = "Hello World!"; Intent notificationIntent = new Intent(this,Second.class);

Notification

35

Android Application Development


PendingIntent contentIntent notificationIntent, 0); = PendingIntent.getActivity(this, contentTitle, 0,

notification.setLatestEventInfo(context, contentIntent);

contentText,

mNotificationManager.notify(1, notification); } }

8.2.2

Custom Status Bar Notification

Steps Involved

For a custom a statusBar Notification user, layout

first create a

Populate the layout with the desired Values setcontentview for notification object
Figure 25 : Custom S tatusbar Notification

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:background="#6495ed"> <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_marginRight="10dp" /> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/image"/> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/image" android:layout_below="@id/title" /> </RelativeLayout>

Notification

36

Android Application Development


package com.soulastral.customstatusbarnotification; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.widget.RemoteViews; public class CustomStatusbarNotificationActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); int icon = R.drawable.ic_launcher; CharSequence tickerText = "Hello"; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custumlayout); contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher); contentView.setTextViewText(R.id.title, "Custom notification"); contentView.setTextViewText(R.id.text, "This is a custom layout"); notification.contentView = contentView; Intent notificationIntent = new Intent(this, CustomStatusbarNotificationActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.contentIntent = contentIntent; mNotificationManager.notify(1, notification); } }

8.3 Dialogs
8.3.1 Simple Dialogs

In the Activity class after the set content view write the codes given below

Notification

37

Android Application Development 8.3.1.1 Dialogs with Button The below code creates a dialog with buttons
final CharSequence[] items = {"Red", "Green", "Blue"};
Figure 26 : Dialog with Button

AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Pick a color"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); } }); AlertDialog alert = builder.create(); alert.show();

8.3.1.2 Adding a list The below code creates a dialog with list
final CharSequence[] items = {"Red", "Green", "Blue"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Pick a color"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); } }); AlertDialog alert = builder.create(); alert.show();

Figure 27 : Dialog with List

8.3.1.3 Adding Radio Buttons The below code adds radio button to the dialog

Notification

38

Android Application Development


final CharSequence[] items = {"Red", "Green", "Blue"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Pick a color"); builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); } }); AlertDialog alert = builder.create(); alert.show();
Figure 28 : Dialog with Radio Button

8.3.1.4 Progress Dialog The below code adds progress Dialog to the activity
ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", "Loading. Please wait...", true);

Figure 29 : Progress Dialog

8.3.1.5 Progress Bar The code displays a progress bar dialog


ProgressDialog progressDialog; progressDialog = new ProgressDialog(mContext); progressDialog.setProgressStyle(ProgressDialog. STYLE_HORIZONTAL); progressDialog.setMessage("Loading..."); progressDialog.setCancelable(false);
Figure 30 : Progress BarDialog

8.3.2

Custom Dialogs

Steps Involved

For a custom Dialog user must first create a layout for the Dialog
Figure 31 : Custom Dialog

Notification

39

Android Application Development


Populate the layout with the desired Values setView for dialog

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout_root" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="10dp" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#FFF" /> </LinearLayout>

package com.soulastral.customdialog;

import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView;

public class CustomDialogActivity extends Activity {

Notification

40

Android Application Development


/** Called when the activity is first created. */ AlertDialog.Builder builder; AlertDialog alertDialog;

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

Context mContext = getApplicationContext(); LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);

View layout = inflater.inflate(R.layout.customlayout,(ViewGroup) findViewById(R.id.layout_root));

TextView text = (TextView) layout.findViewById(R.id.text); text.setText("Hello, this is a custom dialog!"); ImageView image = (ImageView) layout.findViewById(R.id.image); image.setImageResource(R.drawable.ic_launcher);

builder = new AlertDialog.Builder(mContext); builder.setView(layout); alertDialog = builder.create(); alertDialog.show(); } }

Notification

41

Android Application Development

9 Storage Based Application Development


Storing data is one of the most important component of each and every application, as each application requires the data to be saved for further use. Android handset provides following storage techniques: Shared Preferences Internal Storage External Storage SQLite Databases Network Connection

We will use a common layout for all the data storage technique mentioned above.

Figure 32 : S torage Techniques

Storage Based Application Development

42

Android Application Development Here is the XML lines of code for the upper layout
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Writing to Storage" android:textAppearance="@android:style/TextAppearance.Medium"/> <EditText android:id="@+id/text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0.3"/> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Write" android:onClick="writefunc" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Retrieved from Storage" android:textAppearance="@android:style/TextAppearance.Medium"/> <EditText android:id="@+id/retrieve" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0.3" android:editable="false"/>

<Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Retrieve" android:onClick="retrievefunc" /> </LinearLayout>

User writes in First EditText and presses Write button, which is then, stored using some data storage technique illustrated below

Storage Based Application Development

43

Android Application Development

9.1 Shared Preferences


To get a SharedPreferences object for your application, use one of two methods: getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter. getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

9.1.1

Writting to SharedPreference

To write values: Call edit() to get a SharedPreferences.Editor. Add values with methods such as putBoolean() and putString(). Commit the new values with commit()
public void writefunc(View v) { SharedPreferences settings = getSharedPreferences("Mypref", 0); SharedPreferences.Editor editor = settings.edit(); editor.putString("text", text.getText().toString()); editor.commit(); Toast.makeText(getApplicationContext(), "Written", Toast.LENGTH_LONG).show();

Storage Based Application Development

44

Android Application Development 9.1.2 Retrieving Shared preferences

To read values, use SharedPreferences methods such as getBoolean() and getString().


public void retrievefunc(View v) { SharedPreferences settings = getSharedPreferences("Mypref", 0); String temp=settings.getString("text", "Unable to retrieve"); retrieve.setText(temp); } }

9.2 Internal Storage


You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed. 9.2.1 Writing to Internal Storage

To create and write a private file to the internal storage:

1. Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream. 2. Write to the file with write(). 3. Close the stream with close().
public void writefunc(View v) { String string = text.getText().toString(); try {

Storage Based Application Development

45

Android Application Development


FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close(); } catch (Exception e) { // TODO: handle exception } Toast.makeText(getApplicationContext(), "Written", Toast.LENGTH_LONG).show(); }

MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application. Other modes available are: MODE_APPEND,MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.

9.2.2

Retrieving from Internal Storage

To read a file from internal storage: Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. Read bytes from the file with read(). Then close the stream with close().
public void retrievefunc(View v) { String temp; byte[] buffer=new byte[10]; try { FileInputStream fos = openFileInput(FILENAME); fos.read(buffer); fos.close(); } catch (Exception e) { // TODO: handle exception } temp=new String(buffer); retrieve.setText(temp); }

Storage Based Application Development

46

Android Application Development

9.3 External Storage


Every Android-compatible device supports a shared "external storage" that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer. 9.3.1 Writing to External Storage

The below method writes to External Storage


public void writefunc(View v) { String string = text.getText().toString(); try { File sdCard = Environment.getExternalStorageDirectory(); File dir = new File (sdCard.getAbsolutePath() + "/dir/"); dir.mkdirs(); File file = new File(dir, "test"); FileOutputStream fos = new FileOutputStream(file); fos.write(string.getBytes()); fos.close(); } catch (Exception e) { // TODO: handle exception } Toast.makeText(getApplicationContext(), Toast.LENGTH_LONG).show(); }

"Written",

9.3.2

Retrieving from External Storage

The below code reads from the external Storage


public void retrievefunc(View v) { String temp; byte[] buffer=new byte[10]; try { File sdCard = Environment.getExternalStorageDirectory(); File dir = new File (sdCard.getAbsolutePath() "/dir/test");

Storage Based Application Development

47

Android Application Development


FileInputStream fos = new FileInputStream(dir); fos.read(buffer); fos.close(); } catch (Exception e) { // TODO: handle exception } temp=new String(buffer); retrieve.setText(temp); } }

The below line must be added to the manifest file for the application to work <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

9.4 SQLite Database


Android provides full support for SQLite databases. Any databases you create will be accessible by name to any class in the application, but not outside the application. First a class needs to be created which extends SQLiteOpenHelper. This class on call from activity creates database and its schema.
public class MyDbHelper extends SQLiteOpenHelper { private private private private TEXT);"; static static static static final final final final int DATABASE_VERSION = 1; String DATABASE_NAME = "mydb.db"; String Names_TABLE_NAME = "names"; String Names_TABLE_CREATE ="CREATE TABLE names(names

MyDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(Names_TABLE_CREATE); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // TODO Auto-generated method stub } }

Storage Based Application Development

48

Android Application Development The activity then calls this class when creating the object of the class by passing context as the parameter 9.4.1 Get Database

Create object of MyDbHelper class


void getdatabase() { mdb=new MyDbHelper(this); }

9.4.2

Inserting Data

Insert data in the table


public void writefunc(View v) { try { wdb=mdb.getWritableDatabase(); ContentValues contentValues=new ContentValues(); contentValues.put("names", text.getText().toString()); wdb.insert("names", null,contentValues); Toast.makeText(getApplicationContext(),"Written", Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(getApplicationContext(), Toast.LENGTH_LONG).show(); } }

e.getMessage(),

9.4.3

Deleting Data

Deleting data from table


public void deleterecords() { try { wdb=mdb.getWritableDatabase();

Storage Based Application Development

49

Android Application Development


wdb.delete("names", "names='Akash'", null); } catch (Exception e) { // TODO: handle exception } }

9.4.4

Updating Data

Updating table
public void update() { try { wdb=mdb.getWritableDatabase(); ContentValues cv=new ContentValues(); cv.put("names", "Ram"); wdb.update("names",cv , "names='Akash'", null); } catch (Exception e) { // TODO: handle exception } }

9.4.5

Retrieving Data

Retrieving data from table


public void retrievefunc(View v) //Select Query { String temp=""; rdb=mdb.getReadableDatabase(); Cursor cu=rdb.rawQuery("select * from names", null); if(cu.moveToFirst()) { do { String str = cu.getString(0); temp=temp+"\n"+str; }while(cu.moveToNext()); } retrieve.setText(temp); }

Storage Based Application Development

50

Android Application Development

10 Multimedia
The Android multimedia framework includes support for capturing and playing audio, video and images in a variety of common media types, so that you can easily integrate them into your applications. You can play audio or video from media files stored in your application's resources, from standalone files in the file system, or from a data stream arriving over a network connection, all using the MediaPlayer APIs. You can also record audio, video and take pictures using the MediaRecorder and Camera APIs if supported by the device hardware.

10.1 Audio
10.1.1 To Record
MediaRecorder recorder = new MediaRecorder();recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setOutputFile(path); recorder.prepare(); recorder.start();

10.1.2 To Play

MediaPlayer is the easier way, if you just want to play an audio file in the background,

somewhere in an application.
There are no UI controls here, but of course you can use MediaPlayer.stop(), play(),

seekTo() ,etc.
Just bind the needed functions to a button, gesture, or event. It also throws a lot of exceptions, which you need to catch.

Multimedia

51

Android Application Development


MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1); mediaPlayer.start(); // no need to call prepare(); create() does that for you

public void audioPlayer(String path, String fileName){ //set up MediaPlayer MediaPlayer mp = new MediaPlayer(); mp.setDataSource(path+"/"+fileName); mp.prepare(); mp.start(); } //surround with try-catch

10.2 Tone Generator


Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManager.STREAM_DTMF, 100); Tone Generator Object tone.startTone(int tonetype,int duration in Ms); type value and duration //Start tone with tone //Create

10.3 Video
10.3.1 To Play Video VideoViewvideoView=(VideoView)findViewById(R.id.videoView); videoView.setVideoPath("/sdcard/dcim/100MEDIA/VIDEO0001.3gp"); videoView.start();

Multimedia

52

Android Application Development

11 Mobile Web Apps


Mobile web apps provide flexibility and code reusability. The web apps made for desktop application can easily be converted to mobile web apps with minimum efforts in doing the same. Languages: HTML, CSS, JAVASCRIPT, JQUERY Features that mobile apps should have are:

Linking with native libraries (Accelerometer, camera, etc.) UI Look and feel like native application (Buttons, Labels, etc.) Navigation like native application (Screen sliding, orientations, etc.)

11.1 Linking with native Libraries


Native controls in the HTML can be implemented using phonegap framework which consists of a webview which links to all the native phone controls like accelerometer, camera, compass, location based services and provides the navigator access to the above mentioned controls.

11.2 UI Look and feel like native application

Manually: UI look and feel in mobile is controlled using CSS. One can manually write the cascading style sheets(Require a lot of effort to write CSS file that matches the native look)

Existing : One can use existing style sheets like provided by IUI which produces native type look

Mobile Web Apps

53

Android Application Development

11.3 Navigation like native application

Manually : If the CSS is written manually the button events, effects should also be written by the developer using JavaScript and Jquery

Existing : If the developer is using existing style sheets like provided by IUI , the user also gets the script file which controls the navigation effects and events

11.4 Advantages

Code Reusability Code Simplification

11.5 Disadvantages

Decrease in battery performance due to increased frameworks/layers

Mobile Web Apps

54

Android Application Development

12 Game Development
Android supports game development, as a result of this several games can be found in android Play. Some types of games in the android are:

Accelerometer Based Games Simple Canvas Based Games 3d Games

12.1 Accelerometer Based Games


Android handsets provide sensors. Accelerometer is one such sensor responsible to detect movements in x, y and z directions. Accelerometer based games cannot be tested on Android Emulator.

12.2 Getting Accelerometer Readings


The below code captures the accelerometer readings
import android.app.Activity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.widget.TextView; public class AccelerometerActivity extends Activity implements SensorEventListener{ private SensorManager sensorManager; TextView xCoor, yCoor, zCoor; @Override public void onCreate(Bundle savedInstanceState) {

Game Development

55

Android Application Development


super.onCreate(savedInstanceState); setContentView(R.layout.main); xCoor=(TextView)findViewById(R.id.xcoor); // create X axis object yCoor=(TextView)findViewById(R.id.ycoor); // create Y axis object zCoor=(TextView)findViewById(R.id.zcoor); // create Z axis object sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Se nsor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYP E_LIGHT), SensorManager.SENSOR_DELAY_NORMAL); } public void onAccuracyChanged(Sensor sensor, int accuracy) { public void onSensorChanged(SensorEvent event) { if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){ // assign directions float x=event.values[0]; float y=event.values[1]; float z=event.values[2]; xCoor.setText("X: "+x); yCoor.setText("Y: "+y); zCoor.setText("Z: "+z); } }

12.3 Building Game


12.3.1 Main Activity class

Create a main activity class. Pass Activity context and sensor manager to the custom view object created.

Game Development

56

Android Application Development

Set the content view of activity as the newly created custom view object

12.3.2 Create Custom View

Extend the View in the Custom View which implements SensorEventListener Register Accelerometer Sensor event Listener Each view consists of canvas which is used in game developments. Drawing in canvas is carried out using onDraw() method

12.3.3 Creating Stage Screens


Set Static background using setBackgroundResource(R.drawable.img_name); Create a stage screens using Gimp Set the above created (with transparency channel) in the canvas using

bg=Bitmap.createScaledBitmap(bg,getWidth(),getHeight(),true); canvas.drawBitmap(bg, 0, 0,null);

onSensorChanged()

Is called when there is movements in X, Y and Z directions Update the positions of the x, y and z To bring about changes in canvas call invalidate() method

The program consists of a static sand background drawn on Custom View. The Second image is the spiral image which consists of transparency and spirals Using the check conditions for transparency, the ball movement is controlled. The ball moves in the transparent region and stucks in the any other region which is opaque.

Game Development

57

Android Application Development

Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile Application Development including Blackberry, Android and J2ME. It helped me in understanding the complete life cycle of application development which starts from analytical phase followed by documentation phase and on verification goes to implementation phase. In my internship I worked in a team with Mr. Vineet Agarwal and Mr. Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always dreamed off.

I got an opportunity to work as a graphic designer for which I used Open Source Gimp. I also got an opportunity to prepare some documentation and user manuals for the ongoing projects of Sevya.

Conclusion

ix

Android Application Development

References
Android Developers: (http://developer.android.com) Google: (http://google.co.in) Wikipedia: (http://www.wikipedia.org/) Mr. Narasayya Donepudi( Co-Founder at Sevya Multimedia) Mr. Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr. Vineet Agarwal (Software Engineer at Sevya Multimedia)

References

Android Application Development

Glossary
Accelerometer : Instrument which get acceleration values of all the axes on movements Activity Android Context Dalvik Dialog Implicit Intents Kernel Notification Sensor SQLite : : : : : : : : : : : A screen for the application An Open source operating system loaded in smart phones Interface to global information about an application environment It runs the executable .dex files A type of Notification Users are not required to define themselves, defined by system Used to call other Activity It is responsible for the interaction of hardware and software A message generated for better user interaction Senses some components like temperature, location, etc. A powerful and lightweight relational database engine available to all applications Tone : Generation of sound at some given Frequency

Glossary

xi

Você também pode gostar