Android Application (Report)
Android Application (Report)
ON
Akash Khaitan
08DDCS547
AT
June 2012
A REPORT
ON
Akash Khaitan
08DDCS547
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.
Station: Duration:
Sevya It. Pvt. Ltd. 5 Months 14 Days 15th June, 2012 Android Application Development
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
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
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
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
Lists ................................................................................................................................ 26 Simple Lists............................................................................................................. 26 Custom Lists ........................................................................................................... 27 Custom Adapter ...................................................................................................... 28 List Activity ............................................................................................................ 29
Listener ........................................................................................................................... 30
Notification ........................................................................................................................... 31 8.1 Toast Notification........................................................................................................... 32 Simple Toast Notification ....................................................................................... 32 Custom Toast Notification ...................................................................................... 32
Status Bar Notifications ................................................................................................. 34 Simple Status Bar Notification ............................................................................... 35 Custom Status Bar Notification .............................................................................. 36
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
Internal Storage .............................................................................................................. 45 Writing to Internal Storage ..................................................................................... 45 Retrieving from Internal Storage ............................................................................ 46
External Storage ............................................................................................................. 47 Writing to External Storage .................................................................................... 47 Retrieving from External Storage ........................................................................... 47
SQLite Database............................................................................................................. 48 Get Database ........................................................................................................... 49 Inserting Data .......................................................................................................... 49 Deleting Data .......................................................................................................... 49 Updating Data ......................................................................................................... 50 Retrieving Data ....................................................................................................... 50
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
Accelerometer Based Games ...................................................................................... 55 Getting Accelerometer Readings ................................................................................ 55 Building Game ............................................................................................................ 56 Main Activity class ................................................................................................. 56 Create Custom View ............................................................................................... 57 Creating Stage Screens............................................................................................ 57
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
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
Architecture
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
A modern web browser engine which powers both the Android browser and an embeddable web view 2.2.6 SGL
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
Architecture
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
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.
Activity
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
application-level operations such as launching activities, broadcasting and receiving intents, etc.
3.3 Intents
Intents are
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.
method.
Extras are key/value pairs; the key is always a String. As value you can use the primitive
Activity
Android Application Development Receiving Extra data in sub activitys onCreate() method
Intent intent=getIntent(); String receivedString=intent.getExtras().getString(Value1)
Activity
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
Services
10
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.
User Interface
11
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.
The Android SDK includes some simple layouts to construct UI. The following list
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.
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.
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.
5.1.1.4 TableLayout The Table Layout lets you lay out Views using a grid of rows and columns.
User Interface
14
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
Figure 11 : S pinner
5.2.4
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
User Interface
16
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 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
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.
To add a WebView to your Application, simply include the <WebView> element in your
In order for your Activity to access the Internet and load web pages in a WebView, you
User Interface
19
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
<?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>
Menus
20
Menus
21
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
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
7.1.2
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
Navigation
23
7.1.4
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
} }
7.1.5
On Tab Changed
Navigation
25
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
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
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
Navigation
27
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
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
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
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.
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.
This document summarizes each of these techniques for notifying the user and includes links to full documentation.
Notification
31
The default toast notification the code for which is given below
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
Steps Involved
Notification
32
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
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(); } }
Notification
34
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)
Context context = getApplicationContext(); CharSequence contentTitle = "My notification"; CharSequence contentText = "Hello World!"; Intent notificationIntent = new Intent(this,Second.class);
Notification
35
notification.setLatestEventInfo(context, contentIntent);
contentText,
mNotificationManager.notify(1, notification); } }
8.2.2
Steps Involved
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
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();
8.3.1.3 Adding Radio Buttons The below code adds radio button to the dialog
Notification
38
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);
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
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;
Notification
40
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);
Notification
41
We will use a common layout for all the data storage technique mentioned above.
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"/>
User writes in First EditText and presses Write button, which is then, stored using some data storage technique illustrated below
43
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();
44
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 {
45
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
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); }
46
"Written",
9.3.2
47
The below line must be added to the manifest file for the application to work <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
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 } }
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
9.4.2
Inserting Data
e.getMessage(),
9.4.3
Deleting Data
49
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
50
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
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.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
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.)
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
53
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
11.5 Disadvantages
54
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:
Game Development
55
Create a main activity class. Pass Activity context and sensor manager to the custom view object created.
Game Development
56
Set the content view of activity as the newly created custom view object
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
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
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
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
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
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